Java 12 introduces expressions to Switch statement and released it as a preview feature. Java 13 added a new yield construct to return a value from switch statement. With Java 14, switch expression now is a standard feature.
- Each case block can return a value using yield statement.
- In case of enum, default case can be skipped. In other cases, default case is required.
Example
Consider the following example −
Java14Switch.java
public class Java14Switch {
public static void main(String[] args) {
System.out.println("Old Switch");
System.out.println(getDayTypeOldStyle("Five"));
System.out.println(getDayTypeOldStyle("Eight"));
System.out.println(getDayTypeOldStyle(""));
System.out.println("New Switch");
System.out.println(getDayType("Six"));
System.out.println(getDayType("Three"));
System.out.println(getDayType(""));
}
public static String getDayType(String day) {
var result = switch (day) {
case "One", "Three", "Five", "Seven", "Nine": yield "Odd Number";
case "Two", "Four", "Six", "Eight": yield "Even Number";
default: yield "Invalid Number.";
};
return result;
}
public static String getDayTypeOldStyle(String day) {
String result = null;
switch (day) {
case "One":
case "Three":
case "Five":
case "Seven":
case "Nine":
result = "Odd Number";
break;
case "Two":
case "Four":
case "Six":
case "Eight":
result = "Even Number";
break;
default:
result = "Invalid Number.";
}
return result;
}
}
Output
Compile the class using javac compiler as follows −
>javac -Xlint:preview --enable-preview -source 14 Java14Switch.java
>java --enable-preview Java14Switch
It should produce the following output −
Old Switch
Odd Number
Even Number
Invalid Number.
New Switch
Even Number
Odd Number
Invalid Number.