Language beginner

Switch expressions

Switch as an expression that returns a value — no break, no fall-through.

✕ 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";
};
🎯

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
Since JDK
14
Difficulty
beginner
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.

Share 𝕏 🦋 in