Java 12 introduces expressions to Switch statement and released it as a preview feature. Following are the changes introduced in case of new switch with expressions −
- No fallthrough.
- No break statment required to prevent fallthrough.
- A single case can have multiple constant labels.
- Default case is compulsary now.
Consider the following program −
Java12SwitchCase.java
public class Java12SwitchCase {
public static void main(String[] args) {
// 1. Old style of switch case with multiple cases
System.out.println("*** Old Switch ***");
System.out.println(checkEvenOrOddOldStyle(6));
System.out.println(checkEvenOrOddOldStyle(10));
System.out.println(checkEvenOrOddOldStyle(3));
// 2. Single case can have multiple constant labels with break statement.
System.out.println("*** New Switch with break ***");
System.out.println(checkEvenOrOddNewStyleWithBreak(6));
System.out.println(checkEvenOrOddNewStyleWithBreak(10));
System.out.println(checkEvenOrOddNewStyleWithBreak(3));
// 3. Single case can have multiple constant labels with lambda statement.
System.out.println("*** New Switch with lambda expression ***");
System.out.println(checkEvenOrOddNewStyleWithLambda(6));
System.out.println(checkEvenOrOddNewStyleWithLambda(10));
System.out.println(checkEvenOrOddNewStyleWithLambda(3));
}
public static String checkEvenOrOddNewStyleWithBreak(int number) {
String result = switch(number) {
case 1, 3, 5, 7, 9:
break "Odd Number";
case 2, 4, 6, 8:
break "Even Number";
default:
break "The given number is less than 1 or greater than 9.";
};
return result;
}
public static String checkEvenOrOddNewStyleWithLambda(int number) {
String result = switch(number) {
case 1, 3, 5, 7, 9 -> "Odd Number";
case 2, 4, 6, 8 -> "Even Number";
default -> "The given number is less than 1 or greater than 9.";
};
return result;
}
public static String checkEvenOrOddOldStyle(int number) {
String result = null;
switch (number) {
case 1:
case 3:
case 5:
case 7:
case 9:
result = "Odd Number";
break;
case 2:
case 4:
case 6:
case 8:
result = "Even Number";
break;
default:
result = "The given number is less than 1 or greater than 9.";
}
return result;
}
}
Compile the class using javac compiler with preview command as follows −
C:\hitechpoints\workspace\java12-feature\src>javac -Xlint:preview --enable-preview --release 12 Java12SwitchCase.java
Now run the Java8DateTime as follows −
C:\hitechpoints\workspace\java12-feature\src>java --enable-preview Java12SwitchCase
It should produce the following output −
*** Old Switch ***
Even Number
The given number is less than 1 or greater than 9.
Odd Number
*** New Switch with break ***
Even Number
The given number is less than 1 or greater than 9.
Odd Number
*** New Switch with lambda expression ***
Even Number
The given number is less than 1 or greater than 9.
Odd Number