Pattern matching for instanceof
Combine type check and cast in one step with pattern matching.
Code Comparison
✕ Java 8
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
✓ Java 16+
if (obj instanceof String s) {
System.out.println(s.length());
}
Why the modern way wins
No redundant cast
Type check and variable binding happen in a single expression.
Fewer lines
One line instead of two — the cast line disappears entirely.
Scope safety
The pattern variable is only in scope where the type is guaranteed.
Old Approach
instanceof + Cast
Modern Approach
Pattern Variable
Since JDK
16
Difficulty
beginner
JDK Support
Pattern matching for instanceof
Available
Widely available since JDK 16 (March 2021)
How it works
Pattern matching for instanceof eliminates the redundant cast after a type check. The variable is automatically scoped to where the pattern matches, making code safer and shorter.