instanceof patterns
An instanceof check is almost always followed by a cast to the type that was just tested, which is a line that repeats the test and can disagree with it. The pattern form writes both in one expression and binds the value to a variable of the tested type. It is final in Java 16, so Java 21 has it in full.
The pattern variable
value instanceof String s answers the test and, when it is true, gives the tested value the name s with the type String. The body then calls a String method with no cast:
public class Patterns {
public static void main(String[] args) {
Object[] values = {"hello", 42, 3.5};
for (Object value : values) {
if (value instanceof String s) {
System.out.println("string " + s.length());
} else if (value instanceof Integer n) {
System.out.println("int " + (n + 1));
} else {
System.out.println("other " + value);
}
}
}
}
javac -Xlint:all Patterns.java
java Patterns
string 5
int 43
other 3.5
The second branch binds an Integer and adds one to it, which unboxes the value and is the autoboxing of lesson 029. The third value is a Double, matches neither pattern, and the else branch prints it through toString.
Where the variable exists
The pattern variable exists only where the test that bound it is known to be true. Using it after the if ends is a compile error, and the message is the ordinary one for a name that is not there:
public class Scope {
public static void main(String[] args) {
Object value = "text";
if (value instanceof String s) {
System.out.println(s.length());
}
System.out.println(s);
}
}
javac -Xlint:all Scope.java
Scope.java:7: error: cannot find symbol
System.out.println(s);
^
symbol: variable s
location: class Scope
1 error
The variable is not a local of the method, so there is nothing to use after the branch. The scope is a flow property, not a block: the compiler tracks whether the test must have been true at each line.
The negated check
The flow rule also works backwards. A method that returns early when the value is not a string leaves the rest of the body in a state where the test is known to be true, so the variable is usable after the guard:
public class Flow {
public static void main(String[] args) {
Object[] values = {"", "ok", 7};
for (Object value : values) {
System.out.println(describe(value));
}
}
static String describe(Object value) {
if (!(value instanceof String s)) {
return "not a string";
}
return "string of " + s.length();
}
}
javac -Xlint:all Flow.java
java Flow
string of 0
string of 2
not a string
The empty string has length zero and is still a string, so the first line is not the same as the last. The negation is the shape a method uses when the failure is the short path and the work is the rest of the body.
The guard in the condition
A pattern variable may be read by the rest of the same condition, joined with &&. The second half of the condition runs only when the first half bound the name, so it is safe there:
public class Guards {
public static void main(String[] args) {
Object[] values = {"", "ok", "long enough"};
for (Object value : values) {
System.out.println(label(value));
}
}
static String label(Object value) {
if (value instanceof String s && s.length() > 2) {
return "long string: " + s.toUpperCase();
}
return "short or not a string";
}
}
javac -Xlint:all Guards.java
java Guards
short or not a string
short or not a string
long string: LONG ENOUGH
The order matters and cannot be reversed: s.length() > 2 && value instanceof String s does not compile, because the left side is read before the right side has bound the name. That is the short-circuit rule of lesson 010 working in favour of the pattern.
The cast this replaces
The old form is the test, then a cast, then a local variable. Both methods below print the same line for the same value, and the first is the one a code base written before Java 16 is full of. The old page on instanceof shows the test on its own, before pattern variables existed; this lesson is the modern form:
import java.util.List;
public class OldCast {
public static void main(String[] args) {
List<Object> values = List.of(1, "two", 3L);
for (Object value : values) {
System.out.println(old(value) + " / " + modern(value));
}
}
static String old(Object value) {
if (value instanceof Integer) {
Integer n = (Integer) value;
return "int " + (n * 2);
}
return "other";
}
static String modern(Object value) {
if (value instanceof Integer n) {
return "int " + (n * 2);
}
return "other";
}
}
javac -Xlint:all OldCast.java
java OldCast
int 2 / int 2
other / other
other / other
The pair is the whole argument for the pattern: the two halves of the old method name the type twice, and a reader must check that the cast names the same type as the test. The modern method cannot get that wrong, because there is only one mention of the type.
Exercises
- Make the body of Scope.java use the variable inside the if and remove the line after it, then build.
- Add a Double branch to Patterns.java with its own pattern variable.
- Reverse the two sides of the && in Guards.java and read the error.
- Rewrite the empty-string case of Flow.java to answer "empty" with a second pattern check.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
value instanceof String sdo?Answer
Tests the type and binds the value to s when the test is true
The test and the cast are one expression, and the variable exists only in the true branch.
-
Where may the pattern variable be used?
Answer
Only where the compiler knows the test was true
The scope follows the flow of the program, so an early return also makes the name usable later.
-
What does the old form need that the pattern does not?
Answer
A cast to the tested type
The pattern binds the value with the tested type, so no cast is written.
-
What does this program print?
public class Q1 { public static void main(String[] args) { Object o = "abc"; if (o instanceof String s) { System.out.println(s.length()); } } }Answer
3
The value is a String, the name is bound, and its length is three.
-
What does this program print?
public class Q2 { public static void main(String[] args) { Object o = 5; System.out.println(o instanceof String s); System.out.println(o instanceof Integer n); } }Answer
false then true
The value is an Integer, so only the second pattern matches.
-
What does this program print?
public class Q3 { public static void main(String[] args) { System.out.println(text("abcd")); System.out.println(text("ab")); } static String text(Object o) { if (o instanceof String s && s.length() > 3) { return "long " + s; } return "short"; } }Answer
long abcd then short
The first string is longer than three characters, and the second is not.
-
What does this program print?
public class Q4 { public static void main(String[] args) { System.out.println(describe(1)); System.out.println(describe("x")); } static String describe(Object o) { if (!(o instanceof String s)) { return "no string"; } return "string " + s.length(); } }Answer
no string then string 1
The early return leaves the second call in a state where the pattern is known to be true.
-
What is the first line of the compiler output for this program?
public class Q5 { public static void main(String[] args) { Object o = "x"; if (o instanceof String s) { System.out.println(s); } System.out.println(s.length()); } }Answer
error: cannot find symbol
The name does not exist after the branch, so the compiler reports a missing symbol.
-
Why must
value instanceof String scome befores.length() > 2in the condition?Answer
The left side binds the name that the right side reads
The condition is read left to right, and the name exists only after the pattern.
-
What does the pattern do for a null value?
Answer
The test is false and nothing is bound
instanceof answers false for null, as it always has, and the variable exists only after a true test.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev