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
