Sub topic 1
From instanceof and casts to type patterns
This chapter covers pattern matching for instanceof. It is the first step toward pattern matching in switch and record patterns, which later chapters build on it. By the end you will replace instanceof-and-cast code with type patterns, and you will know where the binding variable is in scope and what the compiler rejects.
Prerequisites
This chapter assumes you already know the following:
- Java classes, interfaces and inheritance, including what a subtype is.
- The
instanceofoperator and reference casts, includingClassCastException. - Basic generics, such as
List<String>. - A JDK 21 or newer installation. Type patterns in
instanceofare final since Java 16, so any recent JDK compiles the examples here.
The problem: test, cast, declare
Before Java 16, checking a type and using the value took three steps that all repeated the same type name:
- Test the type with
instanceof. - Cast the reference to that type.
- Declare a new variable to hold the cast result.
static String describeOld(Object o) {
if (o instanceof String) {
String s = (String) o;
if (!s.isEmpty()) {
return "non-empty string of length " + s.length();
}
}
return "something else";
}The cast is safe only because the test came first. The compiler does not connect the two, so the type appears twice and a copy-paste mistake can make them disagree. If the second type were different, you would get a ClassCastException at run time instead of a compile error.
Type patterns in instanceof
A type pattern combines the type test and the variable declaration. Its form is a type followed by a name:
static String describe(Object o) {
if (o instanceof String s && !s.isEmpty()) {
return "non-empty string of length " + s.length();
}
return "something else";
}Here String s is the pattern. s is a pattern variable, also called a binding variable. At run time, the following happens:
- The expression
ois evaluated. - If the value is an instance of
String, it is assigned tosand the test istrue. - If the value is
nullor not aString, the test isfalseandsis not assigned.
The compiler has already checked that s is a String, so no cast appears in your code.
null never matches
instanceof returns false for null, with or without a pattern. So o instanceof String s is false when o is null, and s is never bound to null. This keeps instanceof patterns free of null checks. The switch form treats null differently, which the chapter on case null covers.
Where the binding variable is in scope
The binding variable is in scope only where the compiler can prove the pattern matched. This is called flow scoping. It follows the control flow of the code, not the braces of a block.
Inside a conjunction
In a && b, the right side runs only if the left side was true. So a binding from the left is usable on the right:
static boolean isLongString(Object o) {
return o instanceof String s && s.length() > 10;
}In the true branch of an if
static int length(Object o) {
if (o instanceof String s) {
return s.length(); // s is in scope here
}
// s is not in scope here
return -1;
}With negation and early exit
A binding can also be in scope after the if. When the negated test guards a branch that cannot complete normally, the pattern must have matched on every path that continues:
static int lengthOrFail(Object o) {
if (!(o instanceof String s)) {
throw new IllegalArgumentException("not a string: " + o);
}
return s.length(); // s is in scope: the if body always throws
}The if body ends with throw, so execution reaches the return only when o instanceof String s was true. The compiler sees this and keeps s in scope after the if. The same holds for return, break and continue in the body.
Where the binding is not in scope
The compiler rejects uses where the pattern might not have matched.
static boolean bad(Object o) {
// Does not compile: s is not definitely matched on the right of ||
return o instanceof String s || s.length() > 3;
}In a || b, the right side runs only when a is false, which means the pattern did not match. The name s is not available there. The reverse works: !(o instanceof String s) || s.isEmpty() compiles, because the right side runs only when the negated test is false, so the pattern matched.
The table summarizes the common cases.
| Expression | Where the binding is in scope | Column | Column | Column | Column |
|---|---|---|---|---|---|
| `x instanceof T t && ...` | In the right operand of `&&` and in the true branch | ||||
| `x instanceof T t \ | \ | ...` | Nowhere on the right side | ||
| `!(x instanceof T t) \ | \ | ...` | In the right operand of `\ | \ | ` |
| `if (!(x instanceof T t)) { return; }` | After the `if` statement | ||||
| `x instanceof T t ? a : b` | In `a`, not in `b` |
Rules and restrictions
The pattern type must be possible
The compiler rejects a pattern when the cast could never succeed. For example, Integer and String are unrelated final classes, so this fails:
static boolean never(Integer i) {
// Does not compile: Integer cannot be cast to String
return i instanceof String s;
}This is the same check the compiler applies to casts.
Unconditional patterns are allowed
Older versions of Java rejected instanceof when the expression's static type was already a subtype of the pattern type. Since Java 21 this is allowed. The test is true whenever the value is not null:
static int len(String text) {
if (text instanceof CharSequence cs) { // legal in Java 21 and newer
return cs.length();
}
return -1; // reached only when text is null
}The code is rarely useful, but the rule explains how patterns behave in switch, where the same idea matters.
Binding variables are not final by default
A binding variable is an ordinary local variable and you may assign to it. If you want to prevent that, write final: o instanceof final String s. A binding variable cannot shadow another local variable that is in scope. Use a different name.
Generics and reifiable types
The test is a runtime check, so the pattern type must be checkable at run time. This is a type that is reifiable, or a generic type whose argument is guaranteed by the static type:
static int count(List<String> list) {
// Fine: the cast from List<String> to ArrayList<String> is checked
if (list instanceof ArrayList<String> al) {
return al.size();
}
return list.size();
}
static void bad(Object o) {
// Does not compile: the type argument cannot be checked at run time
// if (o instanceof List<String> l) { ... }
}For an Object, you can match List<?> and then handle the element type separately.
A worked refactoring: equals
The classic place to see the gain is an equals method. The old style:
final class Point {
private final int x;
private final int y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point other = (Point) o;
return x == other.x && y == other.y;
}
@Override
public int hashCode() { return 31 * x + y; }
}With a type pattern:
final class Point {
private final int x;
private final int y;
Point(int x, int y) { this.x = x; this.y = y; }
@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; }
}The single expression handles null, the wrong type and the field comparison. The class is final, so instanceof is safe here. In a non-final class, an instanceof-based equals can break symmetry with subclasses. Use getClass() or keep the class final.
Common errors
- Using the binding after
||. The compiler reports that the name cannot be resolved. Restructure with&&, or negate the test. - Reusing a name.
if (o instanceof String s)fails if a local variablesis already in scope. - Expecting a match on
null.instanceofis alwaysfalsefornull, so anullinput falls into yourelsepath. - Using an incompatible type. If the compiler says the types are inconvertible, the check could never succeed, so fix the pattern type or the expression's static type.
- Long chains of
else if. A chain ofinstanceofpatterns works, but it does not check that you covered every subtype. The next chapters replace such chains withswitch, which does.
Chains of patterns
A chain of instanceof patterns is a useful bridge to switch:
static double area(Object shape) {
if (shape instanceof Double d) {
return d * d; // a square given as a side length
} else if (shape instanceof Integer i) {
return (double) i * i;
} else if (shape instanceof String s) {
return Double.parseDouble(s) * Double.parseDouble(s);
}
throw new IllegalArgumentException("unsupported: " + shape);
}Each branch has its own binding, and the bindings are scoped to their branch. This works, but the code is long and the order matters only by convention. The switch form in the next chapter expresses the same logic as one expression.
Exercise
The following method does not compile. Explain why, then rewrite the condition so it compiles and returns true only for a non-null string shorter than 3 characters. static boolean shortString(Object o) { return o instanceof String s || s.length() < 3; }
Show answer
In a || b, the right operand runs only when the left operand is false, which means the pattern did not match, so s is not in scope there. Use &&: return o instanceof String s && s.length() < 3;. A null input makes the instanceof test false, so the method returns false for null.
Exercise
What does this method return for the argument null, and what does it return after the if statement for the argument "hi"? static String check(Object o) { if (!(o instanceof String s)) { return "not a string"; } return "string of length " + s.length(); }
Show answer
For null, o instanceof String s is false, so the negation is true and the method returns "not a string". For "hi" the pattern matches, the if body is skipped, and s is in scope after the if because the body always returns. The method returns "string of length 2".