Video in progress

Strong Middle ☕ Core Java

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:

  1. null. The old switch always threw an NPE on null. The new one does too, if there's no case null. You can combine them as case null, default ->.
  2. Order. The first matching case runs. If you put case Integer i before case Integer i when i > 1_000_000, the second can never be reached, and the compiler flags that as an error.
  3. Guards don't help exhaustiveness. case Integer i when i > 0 and case Integer i when i <= 0 are logically complete, but the compiler doesn't know that: you need a case without a guard, or a default.
  4. 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.