โ— Shell
clean mode source โ†—

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