Video in progress
How do case null, guards (when) and case order work in a pattern switch?
In Java 21, a switch throws an NPE on null unless there's a case null. when is an extra condition. Cases are checked from top to bottom; if a broad pattern comes before a narrow one, the compiler reports a "dominance" error.
📖 Answer
String describe(Object o) {
return switch (o) {
case null -> "bo'sh";
case Integer i when i > 1_000_000 -> "katta son";
case Integer i -> "son: " + i;
case String s when s.isBlank() -> "bo'sh matn";
case String s -> "matn: " + s;
default -> o.getClass().getSimpleName();
};
}
The rules:
- null. The old switch always threw an NPE on
null. The new one does too, if there's nocase null. You can combine them ascase null, default ->. - Order. The first matching case runs. If you put
case Integer ibeforecase Integer i when i > 1_000_000, the second can never be reached, and the compiler flags that as an error. - Guards don't help exhaustiveness.
case Integer i when i > 0andcase Integer i when i <= 0are logically complete, but the compiler doesn't know that: you need a case without a guard, or adefault. - Don't do side effects inside a guard: it makes the code hard to read and hard to follow.
You can use patterns with the old case A: (fall-through) syntax too, but falling through into a case that has a pattern variable is forbidden.
Sign up to mark studied questions and save your progress.