Java case
Created By: chatGPT
In Java, the
switch
statement is a control flow statement that allows a variable to be tested for equality against a list of values (cases). Below is a code snippet demonstrating how to use a switch
statement in Java.String day = "Wednesday";
switch (day) {
case "Monday":
System.out.println("Start of the week!");
break;
case "Tuesday":
System.out.println("Second day of the week!");
break;
case "Wednesday":
System.out.println("Midweek day!");
break;
case "Thursday":
System.out.println("Almost the weekend!");
break;
case "Friday":
System.out.println("Last working day!");
break;
case "Saturday":
System.out.println("Weekend starts!");
break;
case "Sunday":
System.out.println("Weekend ends!");
break;
default:
System.out.println("Not a valid day!");
}
In the above code, we declare a String variable
day
and use the switch
statement to check its value. Depending on the value, a different message is printed. The break
statement is used to exit the switch block after executing a case. If none of the cases match, the default
case will be executed.int number = 2;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Not one, two, or three");
}
The
switch
statement can also handle primitive data types such as int
, char
, byte
, and short
. Additionally, since Java 7, switch
can also be used with String values, providing flexibility in how we can control program flow.char grade = 'A';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
case 'D':
System.out.println("Below Average");
break;
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Not a valid grade");
}
In this example, a
char
variable grade
is evaluated using the switch
statement. Each case corresponds to a possible grade and provides feedback accordingly. Remember, using a switch
can be more readable than a long series of if-else
statements.// Example using enum
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Day today = Day.MONDAY;
switch (today) {
case SUNDAY:
System.out.println("Rest day");
break;
case MONDAY:
System.out.println("Start of the work week");
break;
// additional cases
default:
System.out.println("Another day");
}