Background:
Before Java 12, the switch operator was exclusively used as a statement. With the release of Java 12/14, switch expressions were introduced, which expanded the syntax and capabilities of the operator. Switch expressions are designed for more concise and expressive code.
Problem:
The classic switch often leads to errors: a forgotten break results in fall-through, readability issues with many cases, an inability to return a result directly in the expression, and a lack of exhaustive value checking.
Solution:
A switch expression can return a value, use arrow syntax, support exhaustive checking at compile time, and handle null via default. Its syntax is:
String result = switch(day) { case MONDAY, FRIDAY -> "Workday"; case SATURDAY, SUNDAY -> "Weekend"; default -> throw new IllegalArgumentException(); };
Key features:
Can switch work with enums, strings, and null?
It has worked with enums since Java 5 and with strings since Java 7. Null is only handled through default; otherwise, a NPE will occur.
switch(day) { // day == null default: System.out.println("null"); } // works
What happens if not all enum cases are implemented in a switch expression?
The compiler will require a default or implementation for all values. Absence of this will result in a compilation error.
Can break be used in the new type of switch expression?
In the arrow syntax, break is not needed. If using a block (case X -> { ... }), you can use yield to return a value:
int num = switch(x) { case 1 -> 10; case 2 -> { yield 20; } default -> 0; };
Classic switch with int without break:
switch(type) { case 1: actionA(); case 2: actionB(); // invoked for both type==1 and type==2 }
Pros:
Cons:
Using the new switch expression to match enums with results:
String status = switch(orderStatus) { case PAID -> "Paid"; case CANCELED -> "Canceled"; default -> "In Process"; };
Pros:
Cons: