J.VII · Java 25 practice question
What does the following Java 25 program print when testing a `null` value in a pattern-matching `switch`?
void main() {
Object o = null;
String out = switch (o) {
case null -> "empty";
case String s -> s;
default -> "other";
};
System.out.println(out);
}
Check answer and explanation
Correct answer: empty
Explanation
Because `case null` is explicitly handled, the `switch` expression evaluates to `"empty"` without throwing `NullPointerException`.
Common trap
Without `case null`, switching on `null` throws `NullPointerException`, but an explicit `case null` catches it before `default`.
Source: JEP 441: Pattern Matching for switch — Summary
Checked against the cited text on 2026-11-27.