In Java 12, the switch
statement will be extended to allow expression to control the behaviour and the flow of the switch
statement. As a result, it will simplify your coding.
Let's have an example to illustrate the new switch expressions.
Here is an example of the old way to write the switch
statement:
switch (day) { case MON: case TUE: case WED: case THU: case FRI: System.out.println("Weekday"); break; case SAT: case SUN: System.out.println("Weekend"); break; }
The above switch can be rewritten using switch expression as follow:
switch (day) { case MON, TUE, WED, THU, FRI -> System.out.println("Weekday"); case SAT, SUN -> System.out.println("Weekend"); }
As you can see, the new code is shorter, simplier and easy to read. Learn more about switch expression here.
Reference
- https://openjdk.java.net/jeps/325
- https://openjdk.java.net/projects/jdk/12/