Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java instanceof Pattern Matching: Syntax and Scope

Java instanceof pattern matching removes redundant casts. This article explains the syntax, flow scoping rules, record patterns, and pattern matching for switch.

~4 min readJava
#Java#instanceof#pattern matching#type safety
A branching flow diagram illustrating Java instanceof pattern matching, where a type check binds a variable on one path and rejects the object on the other.

Pattern matching for instanceof in Java removes the redundant cast that follows a traditional type check. Instead of testing the type and casting in two separate statements, you declare a pattern variable directly in the instanceof expression, and the compiler restricts its scope to the code paths where the type test is guaranteed to have succeeded.

java
if (obj instanceof String s) { System.out.println(s.length()); }

The variable s is a pattern variable. It is implicitly final and its type is String, so no explicit cast is needed. Like the traditional operator, the pattern form returns false for null, which means a pattern variable bound by a type pattern is never null when it is in scope.

The Problem With Traditional instanceof Casts

Before pattern matching for instanceof was finalized in Java 16, the standard way to check a type and use the value looked like this:

java
if (obj instanceof String) { String s = (String) obj; System.out.println(s.length()); }

The cast is redundant because the instanceof check already proved the type. The check and the cast are separate statements, so the relationship between them is implicit. If code inserted between them reassigns obj, the later cast can fail even though the earlier instanceof test succeeded. Pattern matching collapses the check and the binding into one expression, so there is no window in which the relationship can break.

Core Syntax of Pattern Matching

The pattern form follows the shape obj instanceof Type variableName. The type must be a reference type, and the variable name is required. The pattern variable's type is the tested type, so s is String in the example above.

The pattern variable is in scope only where the compiler can prove the instanceof test succeeded. This is called flow scoping, and it applies across the surrounding control flow, not just the immediate block.

java
if (obj instanceof String s) { // s is in scope here } // s is not in scope here

The same rule applies in a ternary expression:

java
String result = (obj instanceof String s) ? s : "default";

And in a while loop, where the condition is re-evaluated each iteration:

java
while (obj instanceof String s) { obj = s.substring(1); }

In the loop, s is in scope in the body because the condition must have matched for the body to execute.

Flow Scoping Rules

The scope of a pattern variable is determined by the compiler's flow analysis, and the operators around the instanceof change where the variable is available.

With &&, the right operand is only evaluated when the left operand is true, so the pattern variable is in scope there:

java
if (obj instanceof String s && s.length() > 3) { // s is in scope }

With ||, the right operand may be evaluated when the instanceof test failed, so the pattern variable is not in scope there. This code does not compile:

java
if (obj instanceof String s || s.length() > 3) { // compile error: s is not in scope }

With a negated test and an early return, the pattern variable becomes available after the block:

java
if (!(obj instanceof String s)) { return; } // s is in scope here System.out.println(s.length());

The compiler tracks that reaching this point implies the instanceof succeeded. These rules are defined by the Java Language Specification, so they are not implementation-specific.

Record Patterns

Record patterns were finalized in Java 21. They destructure a record's components as part of the type test:

java
record Point(int x, int y) {} if (obj instanceof Point(int x, int y)) { System.out.println(x + y); }

The pattern Point(int x, int y) matches any Point and binds x and y to its components. You can use var for components you do not need:

java
if (obj instanceof Point(int x, var y)) { // only x is used }

Nested patterns combine a record pattern with type patterns:

java
record Circle(Point center, double radius) {} if (obj instanceof Circle(Point(int x, int y), double r)) { System.out.println("Center: " + x + ", " + y); }

A nested pattern does not match when a component is null. A Circle whose center is null fails the Point(int x, int y) pattern, so the if body does not execute.

Pattern Matching in Switch

Pattern matching for switch was finalized in Java 21 too. It uses case labels with type patterns and optional when guards:

java
switch (obj) { case String s when s.length() > 3 -> System.out.println("Long string: " + s); case String s -> System.out.println("Short string: " + s); case Integer i -> System.out.println(i * 2); default -> System.out.println("Unknown type"); }

The when clause is the switch equivalent of combining instanceof with &&. Case order matters: the first case whose pattern matches and whose when guard is true wins, so more specific patterns must appear before more general ones. Unlike instanceof, a switch over a null value throws NullPointerException unless a case null is present.

Runtime Behavior and Performance

At the bytecode level, the pattern form performs the same instanceof type check as the traditional operator. A traditional cast also emits a checkcast instruction; the pattern form does not need one because the compiler already knows the type. JIT behavior can vary by implementation, so the practical benefit is source-level clarity rather than a guaranteed runtime speedup.

The maintainability gain is real. When you refactor a method that uses pattern matching, the compiler catches scope mistakes that would previously require a runtime test. Using a pattern variable outside its valid scope is a compile error, not a ClassCastException.

Compatibility and Migration

These features arrived in stages:

FeatureJava version
instanceof pattern matchingJava 16
Record patternsJava 21
Pattern matching for switchJava 21

A codebase targeting Java 17 can use instanceof pattern matching but not record patterns or pattern matching for switch. Java 21 is the first LTS release with all three features.

Migration is incremental. You can replace traditional instanceof plus cast pairs one at a time, and the semantic behavior is the same for a successful match, so existing tests should continue to pass. The main risk is scope-related: a pattern variable is only available where the compiler can prove the test matched, whereas a manually declared cast variable can have a broader block scope. If existing code depended on a variable outside the matched region, the refactor will fail at compile time rather than runtime, which is exactly the kind of failure the feature is designed to prevent.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.