liveBook · Manning

Pattern matching for switch

As explained in 100 Java Mistakes and How to Avoid Them

Pattern matching for switch is a Java language feature that lets switch cases match values by type or structural pattern and bind pattern variables.

Pattern matching for switch replaces a series of instanceof checks with switch labels that match by type, bind pattern variables, and select an expression result. Java 21 also lets it handle null and default cases explicitly. section 3.2 section 2.7

Convert type checks into a switch expression

A conversion routine can dispatch BigInteger and BigDecimal before the broader Number pattern, then provide a fallback: `return switch (obj) { case BigInteger bigInteger -> bigInteger; case BigDecimal bigDecimal -> bigDecimal.toBigInteger(); case Number number -> BigInteger.valueOf(number.longValue()); case null, default -> BigInteger.ZERO; };` Each case binds a variable of the matched type. section 3.2

Order overlapping patterns from specific to general. Placing Number before BigInteger makes the later BigInteger case unreachable, and the compiler reports the dominance error automatically. This protection does not cover every dominant condition, such as numeric ranges. section 3.2

Use the feature to make type dispatch explicit and reviewable:

  • Prefer mutually exclusive cases where possible, and order a specific type before its supertype. section 3.2
  • Use bound pattern variables instead of repeating casts inside case bodies. section 2.7
return switch (obj) {
    case First first   -> checkFirst(first);
    case Second second -> !(second instanceof Exclude);
    case Third third   -> checkThird(third);
    case null, default -> false;
};

Compare a switch expression with equivalent instanceof branches for three interfaces and an explicit fallback. section 2.7

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains syntax, bound variables, case ordering, and compiler-checked dominance, but stops short of numeric-range analysis.
Examples
Demonstrates BigInteger and BigDecimal conversion plus interface dispatch with First, Second, Third, and Exclude.
What it assumes
Assumes Java type tests, casting, interfaces, and switch expressions while demonstrating pattern variables from the examples.
What you can do after
Build it from scratch by converting instanceof chains into ordered switch patterns with bound variables and explicit fallbacks.
How it connects
Connects pattern matching for switch with instanceof pattern matching, type casting, switch expressions, null handling, and dominance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.