liveBook · Manning

Pattern matching in instanceof

As explained in 100 Java Mistakes and How to Avoid Them

Pattern matching in instanceof is a Java language feature that combines an instanceof type test with conditional pattern variable binding.

Pattern matching in instanceof combines a type test with conditional variable binding. It replaces the repeated type name and explicit cast required by older Java code, while avoiding ClassCastException when the test fails. section 5.3.1

Replace the explicit cast

Older code writes `if (obj instanceof MyType) { MyType myType = (MyType) obj; … }`. Java 16+ allows `if (obj instanceof MyType myType) { … }`, binding `myType` only when the object matches. section 5.3.1

Use the feature to make type-dependent control flow safer and clearer:

  • Extract separate instanceof checks from complex conditions instead of combining casts, &&, and || expressions. section 2.7
  • Prefer the pattern variable inside the guarded branch; the pattern-based expression never throws ClassCastException because it binds only after a successful test. section 5.3.1
  • When Java 21 is available, consider pattern matching for switch for similarly uniform type-based dispatch. section 2.7
if (obj instanceof MyType myType) {
  … // Use myType.
}

Shows the compact Java 16+ form that tests the type and binds the matching value in one expression. section 5.3.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines the syntax and practical benefit, but stops short of detailed pattern scope or language-specification rules.
Examples
Uses legacy and pattern-based instanceof branches, extracted conditional checks, and a Java 21 switch expression.
What it assumes
Assumes familiarity with Java instanceof checks, explicit casts, conditional expressions, and basic control flow.
What you can do after
Apply it via Java 16+ instanceof expressions to replace guarded explicit casts and simplify conditional type handling.
How it connects
Connects instanceof, explicit casts, ClassCastException, short-circuit evaluation, and pattern matching for switch.

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.