Skip to content
Tutorials Center
My learning

Topics

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.

Java
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

Java Patterns, guards and null

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.

Java Record patterns and sealed exhaustiveness

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 i before case Integer i when i > 0 does not compile, as the first one dominates the second.
  • default last, or case null, default. The default label matches everything, so it goes last; a pattern label after default is a compile error.
  • Arrow form is expression-friendly, and yield returns a value from a block in the colon form. Prefer arrows for new code.
  • Remove the default branch 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 (IncompatibleClassChangeError for 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 invokedynamic type switch; for a few cases the cost is similar to an instanceof chain.
  • Qualified enum names can be used as case constants next to patterns when the selector is a sealed interface that enums implement.