Switch expressions & pattern matching
The modern, fall-through-free switch that returns a value.
Switch that returns a value
Since Java 14, switch can be an expression using the arrow form — no break, no fall-through, and it produces a value:
String name = switch (day) {
case 1 -> "Mon";
case 2, 3 -> "midweek"; // multiple labels
default -> "?";
};
Each arm is independent — there is no fall-through. Multiple labels share an arm with commas. For a multi-statement arm, use a block and yield to produce the value:
int size = switch (s) {
case "S" -> 1;
default -> {
int n = compute(s);
yield n;
}
};
Modern switches also support pattern matching (Java 21): case Integer i -> matches by type and binds i. With sealed types the compiler can even check exhaustiveness.