Switch expressions
Code Comparison
String msg;
switch (day) {
case MONDAY:
msg = "Start";
break;
case FRIDAY:
msg = "End";
break;
default:
msg = "Mid";
}
String msg = switch (day) {
case MONDAY -> "Start";
case FRIDAY -> "End";
default -> "Mid";
};
Why the modern way wins
๐ฏ
Returns a value
Assign the switch result directly โ no temporary variable needed.
๐ก๏ธ
No fall-through
Arrow syntax eliminates accidental fall-through bugs from missing break.
โ
Exhaustiveness check
The compiler ensures all cases are covered.
Old Approach
Switch Statement
Modern Approach
Switch Expression
JDK Support
Switch expressions
Available
Widely available since JDK 14 (March 2020)
How it works
Switch expressions return a value directly, use arrow syntax to prevent fall-through bugs, and the compiler verifies exhaustiveness. This replaces the error-prone statement form.
Related Documentation
Proof