Sub topic 1
Java Pattern Matching for instanceof
Prerequisites
This chapter assumes basic Java syntax, classes, inheritance, reference casts, and Boolean operators such as &&. You should also know that instanceof tests whether an object has a particular runtime type.
A quick recap of instanceof
The expression value instanceof Type evaluates to true when value refers to an object whose type is Type or a subtype of Type. It evaluates to false for null.
public class Main {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String) {
System.out.println("It is a string");
}
}
}The test does not change the declared type of value. Inside the block, value is still declared as Object.
Why check-then-cast is awkward
To use String methods, traditional Java code repeats the type:
public class Main {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length());
}
}
}The explicit cast is safe because the instanceof test succeeded. However, the code names String twice and introduces a separate variable. Pattern matching removes this repetition.
Your first type pattern
A type pattern combines the type test with a variable declaration:
public class Main {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String text) {
System.out.println(text.length());
}
}
}String text is the pattern. Java tests whether value is a String. If it is, Java casts it and assigns the result to text.
What a binding variable is
text is called a binding variable. It is bound to the matched object and has the type written in the pattern, String. You can call String methods on it without another cast.
The variable exists only where Java can prove that the pattern matched. This rule is called flow scoping. The next chapter examines how conditions and early returns affect that scope.
Exercise
What type does the binding variable text have in value instanceof String text?
Show answer
It has type String.