Errors beginner

Null case in switch

Handle null directly as a switch case — no separate guard needed.

✕ Java 8
// Must check before switch
if (status == null) {
    return "unknown";
}
return switch (status) {
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
✓ Java 21+
return switch (status) {
    case null    -> "unknown";
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
🎯

Explicit

null handling is visible right in the switch.

🛡️

No NPE

Switch on a null value won't throw NullPointerException.

📐

All-in-one

All cases including null in a single switch expression.

Old Approach
Guard Before Switch
Modern Approach
case null
Since JDK
21
Difficulty
beginner
Null case in switch
Available

Widely available since JDK 21 LTS (Sept 2023)

How it works

Pattern matching switch can match null as a case label. This eliminates the need for a null check before the switch and makes null handling explicit and visible.

Share 𝕏 🦋 in