Pattern matching for instanceof

Pattern matching for instanceof joins the type test and the cast: obj instanceof String s tests the type and, when the test passes, gives you s already typed as String. This page explains what the compiler generates and where the new variable exists, then shows guard clauses, equals methods, reading values from parsed JSON, the compiler's rules, a shadowing trap, and the primitive patterns previewed in Java 25.

Contents

What a type pattern is

Before Java 16, an instanceof test was nearly always followed by a cast to the type just tested: if (o instanceof String) { String s = (String) o; ... }. The type is written twice, and the cast is a place for mistakes, such as casting to a different type than the one tested after a refactoring. A type pattern merges the two. In o instanceof String s, String s is the pattern: if o is a String, the expression is true and the new binding variable s holds o as a String.

Underneath nothing new happens at run time. The compiler turns the pattern into the same instanceof and checkcast bytecode instructions as the old two-step code; disassembling both versions of the first example below with javap -c shows identical instructions. The new part is in the compiler: it decides where s may be used by working out where the test is known to be true. This is called flow scoping, and it is what makes guard clauses such as if (!(o instanceof String s)) return; work.

Pattern matching with instanceof, by version
FeatureSinceBest for
Type patterns o instanceof String s (JEP 394)Java 16, preview in 14 and 15Replacing test-then-cast code
Record patterns o instanceof Point(int x, int y) (JEP 440)Java 21Taking records apart
Unconditional patterns, such as a String tested against CharSequence csJava 21Generic code; earlier versions reject them
Primitive types in patterns n instanceof byte b (JEP 455, 488, 507)Preview in Java 23, 24 and 25Range checks before narrowing conversions

The programs below were compiled and run on JDK 25. All except the last use only Java 21 features; the last one uses a preview feature and needs --enable-preview.

Before and after, with conditions on the binding

The describe method combines each type test with a condition on the bound value. The inputs pair a passing and a failing value for each condition: a padded and a blank string, 7 and -7, a list with elements and an empty one, and finally null.

Java
import java.util.List;

public class BeforeAfter {

    // Before Java 16: test, then cast to the type that was just tested
    static int oldStyle(Object o) {
        if (o instanceof String) {
            String s = (String) o;
            return s.length();
        }
        return -1;
    }

    // Java 16+: the test declares a binding variable s of type String
    static int newStyle(Object o) {
        if (o instanceof String s) {
            return s.length();
        }
        return -1;
    }

    static String describe(Object o) {
        // The binding is usable on the right of && because that part only runs if the test passed
        if (o instanceof String s && !s.isBlank()) {
            return "text \"" + s.strip() + "\"";
        }
        if (o instanceof Integer i && i > 0) {
            return "positive int " + i;
        }
        if (o instanceof List<?> list && !list.isEmpty()) {
            return "list starting with " + list.get(0);
        }
        return "other: " + (o instanceof String s ? "\"" + s + "\"" : o);
    }

    public static void main(String[] args) {
        System.out.println(oldStyle("hello") + " " + newStyle("hello") + " " + newStyle(42));
        for (Object o : new Object[] {"  hi  ", "   ", 7, -7, List.of("a", "b"), List.of(), null}) {
            System.out.println(describe(o));
        }
    }
}

Output:

Output
5 5 -1
text "hi"
other: "   "
positive int 7
other: -7
list starting with a
other: []
other: null
  • The first line shows the old and new styles give the same result: 5 for "hello", and -1 for the integer 42.
  • The blank string passes the type test but fails !s.isBlank(), so it falls through to the last line, as do -7 and the empty list.
  • null instanceof String s is simply false, so a pattern test is also a null check. No input threw an exception.
  • String s is declared twice in describe, in the first if and on the last line. That is legal because each binding exists only where its own test is true.

Where the binding variable is in scope

A binding is in scope exactly where the compiler can prove the test succeeded:

Scope of the binding s in common forms
CodeIs s usable?
if (o instanceof String s) { ... }Inside the if block
o instanceof String s && s.isEmpty()Yes, right of &&
o instanceof String s || s.isEmpty()No: the right side runs only when the test failed
if (!(o instanceof String s)) return; ...Yes, after the if, for the rest of the block
o instanceof String s ? s.length() : 0Only in the true branch
while (x instanceof String s && ...)In the rest of the condition and the loop body

The program shows the negated guard clause, a binding in a while condition, and a ternary. The first array stops at the empty string after two items; the second stops at the integer after one.

Java
public class FlowScoping {

    // After the negated test returns early, s is in scope for the rest of the method
    static String shout(Object o) {
        if (!(o instanceof String s)) {
            return "not a string";
        }
        return s.toUpperCase() + "!";
    }

    // The binding also flows into a loop condition and its body
    static int countLeadingStrings(Object[] items) {
        int i = 0;
        while (i < items.length && items[i] instanceof String s && !s.isEmpty()) {
            i++;
        }
        return i;
    }

    // Ternaries work the same way: s exists only in the true branch
    static int lengthOrZero(Object o) {
        return o instanceof String s ? s.length() : 0;
    }

    public static void main(String[] args) {
        System.out.println(shout("hey"));
        System.out.println(shout(3.14));
        System.out.println(countLeadingStrings(new Object[] {"a", "b", "", "c"}));
        System.out.println(countLeadingStrings(new Object[] {"a", 1, "c"}));
        System.out.println(lengthOrZero("four") + " " + lengthOrZero(null));
    }
}

Output:

Output
HEY!
not a string
2
1
4 0
  • shout("hey") returned HEY!: after the early return, the compiler knows o is a String for the rest of the method, so s is usable there. This keeps the main logic unindented.
  • The loop counted 2 and 1. The binding is re-tested on every iteration, so s always refers to the current element.
  • lengthOrZero(null) returned 0 without a null check.

Writing equals with a pattern

An equals method has to check the type, cast and compare fields, and with a pattern all three fit in one boolean expression. The test calls cover an equal point, a point with the numbers swapped, an object of another type and null.

Java
public class EqualsPattern {

    static final class Point {
        private final int x;
        private final int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        // One expression: the type test, the cast and the field checks
        @Override
        public boolean equals(Object o) {
            return o instanceof Point p && x == p.x && y == p.y;
        }

        @Override
        public int hashCode() {
            return 31 * x + y;
        }
    }

    public static void main(String[] args) {
        Point a = new Point(1, 2);
        System.out.println("equal point:     " + a.equals(new Point(1, 2)));
        System.out.println("different point: " + a.equals(new Point(2, 1)));
        System.out.println("a String:        " + a.equals("1,2"));
        System.out.println("null:            " + a.equals(null));
    }
}

Output:

Output
equal point:     true
different point: false
a String:        false
null:            false

Because instanceof is false for null, equals(null) returns false without a separate check. Point is final on purpose: with instanceof, a subclass instance can equal a parent instance, which breaks the symmetry rule of equals if the subclass adds fields. For a final class or a record, which generates equals for you, the problem does not arise. See equals and hashCode for the full contract.

Reading values from parsed JSON or YAML

A common real use is data whose types are only known at run time, such as the Map<String, Object> a JSON or YAML parser returns. The sample map holds an Integer, a Double, a Long inside a nested map, a string that means a boolean, and a list, because parsers differ in which number and boolean types they produce.

Java
import java.util.List;
import java.util.Map;

public class ConfigReader {

    // Values as a JSON or YAML parser returns them: String, Number, Boolean, List, Map
    static final Map<String, Object> CONFIG = Map.of(
            "name", "orders-service",
            "port", 8080,
            "timeoutSeconds", 2.5,
            "debug", "yes",
            "hosts", List.of("a.example", "b.example"),
            "db", Map.of("url", "jdbc:h2:mem:test", "pool", 10L));

    static int intValue(Map<String, Object> m, String key, int fallback) {
        // Number covers Integer, Long and Double without knowing which one the parser chose
        if (m.get(key) instanceof Number n && n.doubleValue() == n.intValue()) {
            return n.intValue();
        }
        return fallback;
    }

    static boolean boolValue(Map<String, Object> m, String key) {
        Object v = m.get(key);
        if (v instanceof Boolean b) {
            return b;
        }
        return v instanceof String s && (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("yes"));
    }

    @SuppressWarnings("unchecked")
    static Map<String, Object> section(Map<String, Object> m, String key) {
        // Map<?, ?> is the most a pattern can check; the cast to <String, Object> is unchecked
        if (m.get(key) instanceof Map<?, ?> sub) {
            return (Map<String, Object>) sub;
        }
        return Map.of();
    }

    public static void main(String[] args) {
        System.out.println("port:    " + intValue(CONFIG, "port", 80));
        System.out.println("timeout: " + intValue(CONFIG, "timeoutSeconds", 30)
                + "  (2.5 is not a whole number, so the fallback is used)");
        System.out.println("missing: " + intValue(CONFIG, "retries", 3));
        System.out.println("debug:   " + boolValue(CONFIG, "debug"));
        if (CONFIG.get("hosts") instanceof List<?> hosts && !hosts.isEmpty()) {
            System.out.println("hosts:   " + hosts.size() + ", first " + hosts.get(0));
        }
        Map<String, Object> db = section(CONFIG, "db");
        System.out.println("db pool: " + intValue(db, "pool", 5) + " (stored as a Long)");
        if (db.get("url") instanceof String url && url.startsWith("jdbc:")) {
            System.out.println("db url:  " + url.substring(5));
        }
    }
}

Output:

Output
port:    8080
timeout: 30  (2.5 is not a whole number, so the fallback is used)
missing: 3
debug:   true
hosts:   2, first a.example
db pool: 10 (stored as a Long)
db url:  h2:mem:test
  • Testing against Number n instead of Integer accepted both the Integer 8080 and the Long 10 in the db section. Testing for Integer alone would have missed the pool size and silently used the fallback 5.
  • 2.5 is a Number but not a whole one, so the extra condition n.doubleValue() == n.intValue() rejected it and the fallback 30 was used instead of truncating to 2.
  • m.get(key) instanceof Number n also handles a missing key: get returns null, the test is false, and "retries" got its default 3.
  • For generic types, a pattern can only test what exists at run time. instanceof Map<?, ?> sub is allowed; checking for Map<String, Object> is not, so section still needs an unchecked cast.

What the compiler rejects

The rules are clearest from the compiler's own messages. The program compiles eight one-line method bodies in memory with the javax.tools API and prints what javac reports for each.

Java
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

// Compiles one-line method bodies in memory and prints what javac says about each
public class InstanceofRules {

    public static void main(String[] args) {
        check("binding used after ||",
                "Object o = 1; boolean b = o instanceof String s || s.isEmpty();");
        check("binding used after &&",
                "Object o = 1; boolean b = o instanceof String s && s.isEmpty();");
        check("generic type from Object",
                "Object o = 1; if (o instanceof java.util.List<String> l) { }");
        check("generic type from Collection<String>",
                "java.util.Collection<String> c = java.util.List.of();"
                        + " if (c instanceof java.util.List<String> l) { }");
        check("types that can never match",
                "Integer i = 1; if (i instanceof String s) { }");
        check("binding with the name of a local",
                "Object o = 1; String s = \"\"; if (o instanceof String s) { }");
        check("pattern type is a supertype of the expression type",
                "String str = \"x\"; if (str instanceof CharSequence cs) { }");
        check("final binding reassigned",
                "Object o = 1; if (o instanceof final String s) { s = \"y\"; }");
    }

    static void check(String label, String body) {
        String source = "class T { void m() { " + body + " } }";
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
        JavaFileObject file = new SimpleJavaFileObject(
                URI.create("string:///T.java"), JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return source;
            }
        };
        boolean ok = javac.getTask(null, null, diags,
                List.of("-d", System.getProperty("java.io.tmpdir")), null, List.of(file)).call();
        System.out.println(label + ": " + (ok ? "compiles" : ""));
        for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
            String text = d.getMessage(Locale.ENGLISH).strip();
            System.out.println("  error: " + String.join(" ", text.split("\\s*\\n\\s*")));
        }
    }
}

Output:

Output
binding used after ||: 
  error: cannot find symbol symbol:   variable s location: class T
binding used after &&: compiles
generic type from Object: 
  error: java.lang.Object cannot be safely cast to java.util.List<java.lang.String>
generic type from Collection<String>: compiles
types that can never match: 
  error: incompatible types: java.lang.Integer cannot be converted to java.lang.String
binding with the name of a local: 
  error: variable s is already defined in method m()
pattern type is a supertype of the expression type: compiles
final binding reassigned: 
  error: cannot assign a value to final variable s
  • After || the binding does not exist, so s is "cannot find symbol". After && it compiles.
  • Object cannot be tested against List<String>, because generic type arguments are erased at run time: "cannot be safely cast". From a Collection<String> it compiles, because the only thing left to test is whether it is a List.
  • An Integer can never be a String, so that test is a compile error rather than an always-false check.
  • A binding cannot reuse the name of a local variable in scope. It can reuse a field name, which leads to the trap in the next section.
  • Testing a String against CharSequence cs compiles on Java 21 and later. On Java 16 to 20 this "unconditional pattern" was an error. It is still false for null, because instanceof never matches null.
  • final String s makes the binding unassignable. Without final a binding is an ordinary local and can be reassigned, which is legal but confusing.

Trap: a binding that hides a field

A binding with the same name as a field shadows the field only where the binding is in scope. Elsewhere in the same method, the same name silently means the field. The program uses a static field called name and a binding called name, and calls the method with a string and with a number.

Java
public class ShadowTrap {

    static String name = "field value";

    // The binding 'name' exists only where the test is true.
    // Inside the negated branch, 'name' silently means the static field
    static String greet(Object o) {
        if (!(o instanceof String name)) {
            return "not a string, but name is: " + name;
        }
        return "hello " + name;
    }

    public static void main(String[] args) {
        System.out.println(greet("Ana"));
        System.out.println(greet(42));
    }
}

Output:

Output
hello Ana
not a string, but name is: field value

For "Ana" the binding was in scope and the greeting used it. For 42 the test failed, so inside the negated branch name was the static field, and the message printed "field value" with no compile error or warning. The code looks as if it prints the parameter. Give bindings names that do not match fields, or use this.name for the field so the difference is visible.

Primitive types in instanceof (preview, Java 23 to 25)

JEP 507, the third preview in Java 25 after JEP 455 in Java 23 and JEP 488 in Java 24, extends instanceof to primitive types. It is still a preview: Java 26 previewed it a fourth time (JEP 530) and Java 27 a fifth (JEP 532). For primitives the question is not "is this a subtype" but "can this value be converted without losing information". The inputs were chosen at the edges: -128 is the smallest byte, 1000 and 70,000 fall into the next two ranges, and 16,777,217 (224 + 1) is the first int a float cannot hold.

Java
public class PrimitivePatterns {

    static String fit(int n) {
        if (n instanceof byte b) {
            return n + " fits in a byte: " + b;
        }
        if (n instanceof short s) {
            return n + " fits in a short: " + s;
        }
        return n + " needs an int";
    }

    public static void main(String[] args) {
        for (int n : new int[] {42, -128, 1000, 70000}) {
            System.out.println(fit(n));
        }
        int big = 16777217;                        // 2^24 + 1
        System.out.println(big + " instanceof float:  " + (big instanceof float));
        System.out.println(big + " instanceof double: " + (big instanceof double));
        System.out.println("(float) " + big + " = " + (int) (float) big);
        for (double d : new double[] {250.0, 2.5, 3e10}) {
            System.out.println(d + " instanceof int: " + (d instanceof int i ? "yes, " + i : "no"));
        }
        Object boxed = 7;
        if (boxed instanceof int i) {
            System.out.println("Object holding Integer 7 instanceof int: " + (i + 1));
        }
    }
}

Output (JDK 25, compiled with --enable-preview --release 25 and run with --enable-preview):

Output
42 fits in a byte: 42
-128 fits in a byte: -128
1000 fits in a short: 1000
70000 needs an int
16777217 instanceof float:  false
16777217 instanceof double: true
(float) 16777217 = 16777216
250.0 instanceof int: yes, 250
2.5 instanceof int: no
3.0E10 instanceof int: no
Object holding Integer 7 instanceof int: 8
  • 42 and -128 fit in a byte, 1000 fits in a short, and 70,000 needs an int. This replaces hand-written range checks such as n >= Byte.MIN_VALUE && n <= Byte.MAX_VALUE before a cast.
  • 16,777,217 is not exactly representable as a float: casting it gives 16,777,216, so instanceof float is false. As a double it is exact.
  • 250.0 converts to int exactly; 2.5 has a fraction and 3e10 is beyond the int range, so both are false.
  • An Object holding an Integer matches int i, combining unboxing and the test.

Preview features can change before they become final, so do not use this in production code yet.

Choosing the right test

Which form to use
SituationUse
Test a type and use the valueif (o instanceof Type t)
Reject other types at the top of a methodif (!(o instanceof Type t)) return ...;
Type test plus a conditiono instanceof Type t && condition(t)
Several alternative typesA pattern switch rather than an if chain
Need the record's componentsA record pattern
Exact class match, excluding subclasses (some equals methods)o != null && o.getClass() == getClass()
Numbers from a parserinstanceof Number n, not a specific wrapper type