Java 13 Switch Expressions
This is another preview language feature defined in java 13. Java 13 extends the previous Java 12 Switch expressions by adding a new yield keyword to return a value from switch expression. So break syntax is no longer compiled in Java 13, it uses yield.
As traditional switch statement, there are many break statements make it unnecessarily verbose and hard to debug errors.
// traditional switch statement
switch (number) {
case 1:
System.out.println(“one”);
break;
case 2:
System.out.println(“two”);
break;
befault :
System.out.println(“Zero”);
break;
}
But in Java 12, we can use break to return a value from a switch.
String number=switch (number) {
case 1:
break “one”;
case 2:
break “two”;
befault :
break “Zero”;
}
In Java 13 break replace by yield,
String number=switch (number) {
case 1:
yield “one”;
case 2:
yield “two”;
befault :
yield “Zero”;
}
Arrow syntax is still supported in Java 13.
String number=switch (number) {
case 1 -> “one”;
case 2 -> “two”;
befault ->“Zero”;
}
Related Articles
- Java 13 – New Features Defined in JDK 13
Pingback: ¿Qué significa la nueva palabra clave "rendimiento" en Java 13? - java en Español()