The <code>switch</code> Statement and Expression in Java
Java has two forms of switch now: the classic statement (pre-Java 14, with case : and break) and the modern expression (Java 14+, with case -> and no fall-through). The expression form returns a value and is almost always the better choice.
Modern switch expression (Java 14+)
String label = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
};
- No
breakβ no fall-through. - Multiple values per case with commas.
- Returns a value β enforced to be exhaustive when used as an expression.
Block cases β use yield
int score = switch (grade) {
case 'A' -> 90;
case 'B' -> 80;
default -> {
log.warn("unknown grade " + grade);
yield 0; // return value for this branch
}
};
Classic switch statement
switch (day) {
case MONDAY:
case TUESDAY:
label = "Weekday"; break;
case SATURDAY:
label = "Weekend"; break;
default:
label = "?";
}
Fall-through is the default β forgetting break silently runs the next case. The arrow form eliminates this whole class of bug.
Pattern matching for switch (Java 21+)
String describe(Object o) {
return switch (o) {
case Integer i when i > 0 -> "positive";
case Integer i -> "non-positive int";
case String s -> "string " + s.length();
case null -> "null";
default -> "other";
};
}
Supported types
byte, short, char, int (and wrappers), String, enum, and (since Java 21) any reference type with pattern matching.
Common mistakes
- Forgetting
breakin the classic form β use arrow syntax. - Non-exhaustive expression switch β won't compile without
defaultor covering every case (sealed types help here). - Matching on
nullβ classic switch throws NPE on anullselector. Arrow-form +case nullhandles it explicitly.
Related
Pillar: Java control flow. See also if/else, sealed classes.