Java brought quite a number of vital improvements for developers. Switch Expressions (Standard) is one of the key improvements released under JEP 361. You can download Java 14 by clicking here.
Java 14 - Switch Expressions (Standard)...!!! Share on X
Check out: JAVA 13 Features with examples
JEP 361 – Switch Expressions (Standard)
If you check my article on Java 13 here. You will see that ‘Switch Expression Enhancements’ came under JEP-354 but it was a preview feature. In fact, Java 12 also had this feature as a preview. But, now from Java 14 onwards, this feature is no longer a preview but a standard feature. By standard, it means that you don’t need to specify --enable-preview option to access this feature. It’s permanent now since 14.
Just to give you a brief idea again on what this change is all about. Now, we can return a value from the switch using ‘yield’. This change was there in 13 (in preview mode) but Java 14 extended it a little by allowing to use (->) to return the values as well.
Examples:
Let’s see this example below which returns value through ‘Yield’.
public class SwitchStatement_14_With_Yield {
public static void main(String args[]) {
getValue(1);
}
private static String getValue(int number) {
String value =
switch (number) {
case 1:
yield "Elephant";
case 2, 3:
yield "Dog";
case 4:
yield "Tiger";
case 5, 6, 7, 8:
yield "Cat";
default:
yield "No Idea";
};
return value;
}
}
Let’s see this example below which returns value through ‘Yield’ and ‘Arrow’:
public class SwitchStatement_14_With_Yield_And_Arrow {
public static void main(String args[]) {
getValue(1);
}
private static String getValue(int number) {
String value =
switch (number) {
case 1 - > "Elephant";
case 2, 3 - > "Dog";
case 4 - > "Tiger";
case 5, 6, 7, 8 - > {
yield "Cat";
}
default:
yield "No Idea";
};
return value;
}
}
Java 14 - Switch Expressions (Standard)...!!! Share on X
Other Useful References:
-
- What is new in Java 13