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
