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 and after, with conditions on the binding Where the binding variable is in scope Writing equals with a pattern Reading values from parsed JSON or YAML What the compiler rejects Trap: a binding that hides a field Primitive types in instanceof (preview, Java 23 to 25) Choosing the right test
What a type pattern is
Before Java 16, an instanceofif (o instanceof String) { String s = (String) o; ... }o instanceof String sString soStringsoString
Underneath nothing new happens at run time. The compiler turns the pattern into the same instanceofcheckcastjavap -csif (!(o instanceof String s)) return;
| Feature | Since | Best for |
|---|---|---|
Type patterns o instanceof String s | Java 16, preview in 14 and 15 | Replacing test-then-cast code |
Record patterns o instanceof Point(int x, int y) | Java 21 | Taking records apart |
Unconditional patterns, such as a StringCharSequence cs | Java 21 | Generic code; earlier versions reject them |
Primitive types in patterns n instanceof byte b | Preview in Java 23, 24 and 25 | Range 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 describenull
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:
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
, so it falls through to the last line, as do -7 and the empty list.!s.isBlank() is simply false, so a pattern test is also a null check. No input threw an exception.null instanceof String s is declared twice inString s , in the firstdescribe and on the last line. That is legal because each binding exists only where its own test is true.if
Where the binding variable is in scope
A binding is in scope exactly where the compiler can prove the test succeeded:
| Code | Is s |
|---|---|
if (o instanceof String s) { ... } | Inside the if |
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 |
o instanceof String s ? s.length() : 0 | Only 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
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:
HEY!
not a string
2
1
4 0
returnedshout("hey") : after the earlyHEY! , the compiler knowsreturn is ao for the rest of the method, soString is usable there. This keeps the main logic unindented.s- The loop counted 2 and 1. The binding is re-tested on every iteration, so
always refers to the current element.s returned 0 without a null check.lengthOrZero(null)
Writing equals with a pattern
An equalsnull
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:
equal point: true
different point: false
a String: false
null: false
Because instanceofnullequals(null)Pointfinalinstanceofequalsequals
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>IntegerDoubleLong
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:
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
instead ofNumber n accepted both theInteger 8080 and theInteger 10 in theLong section. Testing fordb alone would have missed the pool size and silently used the fallback 5.Integer - 2.5 is a
but not a whole one, so the extra conditionNumber rejected it and the fallback 30 was used instead of truncating to 2.n.doubleValue() == n.intValue() also handles a missing key:m.get(key) instanceof Number n returnsget , the test is false, and "retries" got its default 3.null- For generic types, a pattern can only test what exists at run time.
is allowed; checking forinstanceof Map<?, ?> sub is not, soMap<String, Object> still needs an unchecked cast.section
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.toolsjavac
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:
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|| is "cannot find symbol". Afters it compiles.&& cannot be tested againstObject , because generic type arguments are erased at run time: "cannot be safely cast". From aList<String> it compiles, because the only thing left to test is whether it is aCollection<String> .List- An
can never be aInteger , so that test is a compile error rather than an always-false check.String - 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
againstString compiles on Java 21 and later. On Java 16 to 20 this "unconditional pattern" was an error. It is still false forCharSequence cs , becausenull never matchesinstanceof .null makes the binding unassignable. Withoutfinal String s a binding is an ordinary local and can be reassigned, which is legal but confusing.final
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 namename
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:
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 namethis.name
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 instanceofintfloat
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--enable-preview
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
before a cast.n >= Byte.MIN_VALUE && n <= Byte.MAX_VALUE - 16,777,217 is not exactly representable as a
: casting it gives 16,777,216, sofloat is false. As ainstanceof float it is exact.double - 250.0 converts to
exactly; 2.5 has a fraction and 3e10 is beyond the int range, so both are false.int - An
holding anObject matchesInteger , combining unboxing and the test.int i
Preview features can change before they become final, so do not use this in production code yet.
Choosing the right test
| Situation | Use |
|---|---|
| Test a type and use the value | if (o instanceof Type t) |
| Reject other types at the top of a method | if (!(o instanceof Type t)) return ...; |
| Type test plus a condition | o instanceof Type t && condition(t) |
| Several alternative types | A if |
| Need the record's components | A |
Exact class match, excluding subclasses (some equals | o != null && o.getClass() == getClass() |
| Numbers from a parser | instanceof Number n |