Sub topic 3
Your first type pattern
This chapter assumes you know basic Java classes, inheritance and subtyping, the instanceof operator with reference casts, the boolean operators &&, || and !, and how to write an equals method. You need Java 16 or later to run the examples.
From test-and-cast to one expression
The traditional idiom uses three steps: test the type, cast, and declare a variable.
Object o = "hello";
if (o instanceof String) {
String s = (String) o;
System.out.println(s.length());
}The type String appears three times. The cast is also safe only because of the test above it, and the compiler does not enforce that link. If someone edits the test later, the cast can silently become unsafe.
A type pattern replaces all three steps.
Object o = "hello";
if (o instanceof String s) {
System.out.println(s.length());
}Here String s is the type pattern. It does two jobs:
- It tests whether the value is an instance of
String. - If the test succeeds, it declares a variable
sof typeStringand assigns the value to it. No cast is written.
The type is now written once, and the test and the cast cannot drift apart.
The syntax
A type pattern in instanceof has this shape:
expression instanceof Type identifierexpressionis any expression whose type is a reference type.Typeis the type you are testing for.identifieris the name of the new variable. The Java Language Specification calls it a pattern variable. Many tutorials call it a binding variable, and the next chapter covers it in detail.
The whole construct is still a boolean expression. You can use it in an if, in a ternary, in a return, or as an operand of &&. It is not a statement, and it does not declare a variable at the point where it appears in the way a local variable declaration does. The compiler decides where the name is usable. That is the subject of the following chapters, so for now use the variable inside the if body, where it always works.
What happens at runtime
The runtime evaluates the left-hand expression once. Then:
- If the value is
null, the result isfalseand nothing is assigned. - If the value is a non-null instance of
Type, the result istrue, and the value is assigned to the new variable. - Otherwise the result is
falseand nothing is assigned.
The assignment involves no cast that can throw ClassCastException. The test and the conversion happen together, so a mismatch is impossible by construction.
A complete example
This program dispatches on the runtime type of an Object, using a chain of patterns.
public class FirstPattern {
static String describe(Object o) {
if (o instanceof String s) {
return "String of length " + s.length();
} else if (o instanceof Integer i) {
return "Integer, next value is " + (i + 1);
} else if (o instanceof java.util.List<?> list) {
return "List with " + list.size() + " elements";
} else {
return "Something else: " + o;
}
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(41));
System.out.println(describe(java.util.List.of(1, 2, 3)));
System.out.println(describe(3.5));
System.out.println(describe(null));
}
}Output:
String of length 5
Integer, next value is 42
List with 3 elements
Something else: 3.5
Something else: nullThree details are worth noticing.
- In the
Integerbranch,i + 1works becauseiis anIntegerthat unboxes to anint. No(Integer) oappears anywhere. - Each pattern variable has its own name. You cannot reuse
sfor a second pattern in the same scope where the first is still visible. describe(null)reaches the finalelse. Everyinstanceoftest is false fornull, so no pattern matches.
The type of the variable
The variable has exactly the type you wrote in the pattern, not the type of the expression. With o instanceof String s, the variable s is a String even though o is an Object. This means you can call String methods on s directly.
The variable behaves like a local variable. You can declare it final if you want to forbid reassignment:
if (o instanceof final String s) {
System.out.println(s.toUpperCase());
}Without final, you may assign to the variable, but doing so has scoping consequences that a later chapter explains. For now, treat it as read-only.
What the compiler checks
The compiler rejects a pattern that can never match. If the expression's type and the pattern's type are unrelated, the code does not compile:
Integer n = 5;
// Does not compile: Integer and String are unrelated, so the test can never succeed.
// if (n instanceof String s) { }The same rule applied to the plain instanceof operator before patterns existed. The pattern form adds one more rule that depends on the Java version.
| Situation | Java 16 to 20 | Java 21 and later |
|---|---|---|
| Expression type is unrelated to the pattern type | Compile error | Compile error |
| Expression type is the same as, or a subtype of, the pattern type | Compile error | Allowed |
| Pattern type is a subtype of the expression type | Allowed | Allowed |
The second row is a common surprise. Suppose String text = "a";. On Java 17, text instanceof String t fails with a message saying the expression type is a subtype of the pattern type. In that case the test would always be true except for null, so the old rule treated it as a mistake. Java 21 removed the restriction. If you must support Java 17, drop the pattern or the test in that situation.
Common errors
Using the variable where it is not matched
The compiler refuses to let you use s in a place where the match may have failed:
static int broken(Object o) {
if (o instanceof String s) {
return s.length();
} else {
// Does not compile: s is not in scope here, because the match did not succeed.
// return s.length();
return -1;
}
}This is the scoping rule in its simplest form. The name exists only where the compiler can prove the match succeeded. The next two chapters describe exactly where that is.
Redeclaring a name that is already in scope
A pattern variable cannot shadow a local variable that is already in scope:
static void clash(Object o) {
String s = "existing";
// Does not compile: s is already defined in this method.
// if (o instanceof String s) { }
}Pick a new name for the pattern variable, such as str, or rename the earlier variable.
Expecting the pattern to work on primitives
In the Java versions this chapter covers, instanceof requires a reference type on the left. If you have an int, there is nothing to test, because its type is already known at compile time. If you have an Object that holds an Integer, use Integer i, as in the example above.
Forgetting that a pattern is not a cast you can reuse
The pattern gives you a new variable of the narrowed type. The original variable o is still an Object. Calling o.length() fails to compile even right after a successful match, so use s.length().
When a type pattern is the right tool
A type pattern shines when you need the narrowed value right away: reading a field, calling a subtype method, or comparing contents. It replaces a cast that you would otherwise write on the next line. If you only need to know the type and never use the value, the plain instanceof Type form is still fine and is not deprecated.
Prefer virtual methods over long chains of patterns when you control the class hierarchy. A chain of instanceof tests is a sign that behavior could belong in the types themselves. Patterns are best for cases where you cannot add methods, such as values of type Object, library types, or equals implementations.
Exercises
Exercise
Rewrite this code with a type pattern, so that the type Integer is written only once. Object o = 42; if (o instanceof Integer) { Integer n = (Integer) o; System.out.println(n + 1); }
Show answer
Object o = 42; if (o instanceof Integer n) { System.out.println(n + 1); }
Exercise
What does this code print, and why? Object o = null; System.out.println(o instanceof String s);
Show answer
It prints false. An instanceof test, including one with a pattern, is false for null. No variable is assigned, and no exception is thrown.
Exercise
A colleague on Java 17 writes the following and gets a compile error. Which Java version change makes it legal, and what should the colleague do on Java 17? String text = "a"; if (text instanceof String t) { System.out.println(t); }
Show answer
On Java 16 to 20, a pattern whose type is the same as or a supertype of the expression's type is a compile error. Java 21 allows it. On Java 17, use text directly, because it is already a String.