why switch statements java code example
Example 1: java switch
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
Example 2: switch expression java
System.out.println(
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
default -> throw new IllegalStateException("Invalid day: " + day);
}
);
Example 3: java switch on what classes
A switch works with the byte, short, char, and int primitive data types.
It also works with enumerated types (discussed in Enum Types), the String
class, and a few special classes that wrap certain primitive types:
Character , Byte , Short , and Integer (discussed in Numbers and Strings).