GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Null case in switch | java.evolved

Home / Errors / Null case in switch
Errors Beginner

Null case in switch

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

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

Switch Expressions Null Safety
Code Comparison
✕ 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";
};
Share 𝕏
See a problem with this code? Let us know.
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
Since JDK
21
Difficulty
Beginner
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
Pattern Matching for switch (JEP 441) ↗
Proof
View proof source ↗
Related patterns
Errors Beginner

Helpful NullPointerExceptions

Java 8
// Old NPE message:
// "NullPointerException"
// at MyApp.main(MyApp.java:42)
// Which variable was null?!
Java 14+
// Modern NPE message:
// Cannot invoke "String.length()"
// because "user.address().city()"
// is null
// Exact variable identified!
Hover to see modern ➜
JDK 14+ →
Errors Intermediate

Record-based error responses

Java 8
// Verbose error class
public class ErrorResponse {
    private final int code;
    private final String message;
    // constructor, getters, equals,
    // hashCode, toString...
}
Java 16+
public record ApiError(
    int code,
    String message,
    Instant timestamp
) {
    public ApiError(int code, String msg) {
        this(code, msg, Instant.now());
    }
}
Hover to see modern ➜
JDK 16+ →
Errors Beginner

Multi-catch exception handling

Pre-Java 7
try {
    process();
} catch (IOException e) {
    log(e);
} catch (SQLException e) {
    log(e);
} catch (ParseException e) {
    log(e);
}
Java 7+
try {
    process();
} catch (IOException
    | SQLException
    | ParseException e) {
    log(e);
}
Hover to see modern ➜
JDK 7+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.