โ— Shell
clean mode source โ†—

Null case in switch

Code Comparison

// Must check before switch
if (status == null) {
    return "unknown";
}
return switch (status) {
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
return switch (status) {
    case null    -> "unknown";
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};

Why the modern way wins

๐ŸŽฏ

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

JDK Support

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.

Related Documentation

Proof