Switch expressions
Switch as an expression that returns a value — no break, no fall-through.
Porównanie kodu
✕ Java 8
String msg;
switch (day) {
case MONDAY:
msg = "Start";
break;
case FRIDAY:
msg = "End";
break;
default:
msg = "Mid";
}
✓ Java 14+
String msg = switch (day) {
case MONDAY -> "Start";
case FRIDAY -> "End";
default -> "Mid";
};
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Switch Statement
Nowoczesne podejście
Switch Expression
Od JDK
14
Poziom trudności
Początkujący
Wsparcie JDK
Switch expressions
Dostępne
Widely available since JDK 14 (March 2020)
Jak to działa
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.
Powiązana dokumentacja