Java / Java 21 Interview Questions
What are switch expressions in Java and how do they differ from switch statements?
Switch expressions (JEP 361, finalised in Java 14) make switch a value-producing expression rather than only a control-flow statement. They use the arrow (->) syntax and require exhaustiveness.
| Aspect | Switch Statement | Switch Expression |
|---|---|---|
| Produces a value | No | Yes — must be exhaustive |
| Syntax | case X: ... break; | case X -> result; or case X -> { ... yield result; } |
| Fall-through | Possible (bug-prone) | Not possible with arrows |
| Exhaustiveness | Not checked | Compiler-enforced (default required unless exhaustive) |
| Multiple labels | No | case A, B, C -> ... (comma-separated) |
// Switch STATEMENT (old style) — fall-through risk
int numLetters;
switch (day) {
case MONDAY: case FRIDAY: case SUNDAY:
numLetters = 6; break;
case TUESDAY:
numLetters = 7; break;
default:
numLetters = 8; break;
}
// Switch EXPRESSION (Java 14+) — exhaustive, no fall-through
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
}; // no default — DayOfWeek is exhaustive
// Multi-line arm with yield
int result = switch (x) {
case 1 -> 10;
case 2 -> {
int y = x * x;
System.out.println("Computing...");
yield y + 5; // yield produces the value from a block arm
}
default -> 0;
};
More Related questions...