Java Reference ยท Object-Oriented Concepts
Pattern matching for switch
Java 21 switch patterns: type and record patterns, when guards, null cases, dominance rules, exhaustiveness and how they differ from classic switch.
Since Java 21 a switch can select a branch by the shape of its value, not only by constant equality. A case label can be a type pattern (case String s), a record pattern (case Point(int x, int y)), null, or a constant, and a pattern can be refined with a guard: case Integer i when i > 10.
This turns long if/else if chains with instanceof into one expression that the compiler can check for completeness. Combined with sealed types, a switch without default is guaranteed to handle every case.
String text = switch (obj) { case Integer i when i > 100 -> "large"; case Integer i -> "int"; case String s -> "string " + s; case null -> "nothing"; default -> "other"; };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Rules
| Rule | Detail |
|---|---|
| Dominance | A case whose pattern is more general than a later one makes the later case a compile error. Put specific cases first. |
| Guards | when takes a boolean expression and can use the bindings. A guarded case does not count toward exhaustiveness unless the guard is the constant true. |
| Exhaustiveness | A switch with patterns (statement or expression) must cover every possible value: add default, or cover all permitted subtypes of a sealed type or all enum constants. |
null |
Without case null, a null selector throws NullPointerException. case null, default -> handles both together. |
| Fall-through | Not allowed past a pattern that declares bindings. |
| Constants with patterns | Allowed for enums, strings and integers when qualified enum constants are used (Java 21). |
| Errors | If a record pattern's accessor throws, the switch throws MatchException. |
Usage notes
- Order matters.
case Integer ibeforecase Integer i when i > 0does not compile, as the first one dominates the second. defaultlast, orcase null, default. Thedefaultlabel matches everything, so it goes last; a pattern label afterdefaultis a compile error.- Arrow form is expression-friendly, and
yieldreturns a value from a block in the colon form. Prefer arrows for new code. - Remove the
defaultbranch on sealed types. That way adding a subtype causes a compile error where you must handle it, rather than a silent fallback. - A switch expression must produce a value for every input. If a sealed hierarchy or enum is extended after your code was compiled, a missing case fails at run time with
MatchException(IncompatibleClassChangeErrorfor enums), another reason to recompile everything together. - Unnamed patterns
_(Java 22) skip components you do not need:case Rect(int w, _). - Performance: the compiler uses an
invokedynamictype switch; for a few cases the cost is similar to aninstanceofchain. - Qualified enum names can be used as case constants next to patterns when the selector is a sealed interface that enums implement.