GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Null case in switch | java.evolved
Errors
Beginner
Null case in switchHandle null directly as a switch case — no separate guard needed. 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";
};
See a problem with this code? Let us know.
Why the modern way wins
🎯
Explicitnull handling is visible right in the switch. 🛡️
No NPESwitch on a null value won't throw NullPointerException. 📐
All-in-oneAll 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
Proof
Related patterns
Errors
Beginner
Helpful NullPointerExceptionsJava 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!
JDK 14+
→
Errors
Intermediate
Record-based error responsesJava 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());
}
}
JDK 16+
→
Errors
Beginner
Multi-catch exception handlingPre-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);
}
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. |