Pattern matching for instanceof
Home / Language / Pattern matching for instanceof
Code Comparison
if (obj instanceof String) {
String s = (String) obj;
int length = s.length();
// do something with 'length'
}
if (obj instanceof String s) {
int length = s.length();
// do something with '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
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.
Related Documentation
Proof