Sub topic 3
Your First Type Pattern
The check-then-cast idiom
This chapter assumes basic Java syntax, inheritance, reference casts, Boolean operators, and the instanceof operator.
An instanceof expression tests whether an object has a particular type. Before Java pattern matching, you usually wrote a test and a cast separately:
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 first line inside the if checks the type. The next line repeats the type in a cast and stores the result in another variable. The cast is safe because the preceding test succeeded, but the compiler cannot connect the two lines as directly as a reader can.
Replacing the cast with a type pattern
A type pattern combines the type test, cast, and variable declaration:
public class Main {
public static void main(String[] args) {
Object value = "hello";
if (value instanceof String text) {
System.out.println(text.length());
}
}
}The pattern is String text.
Stringis the type to test.textis the variable that receives the tested value.texthas the compile-time typeString.- The variable is available inside the
ifbody when the pattern matches.
The compiler effectively performs the cast for you. You do not write (String) value.
How the pattern works
The expression value instanceof String text has a Boolean result, just like an ordinary instanceof expression.
When value refers to a String, the result is true, and text refers to that same object. When the test fails, the body does not run and text cannot be used there.
The pattern variable is often called a binding variable because the successful match binds the object to a new variable name.
Choosing the variable name
Use a name that describes the value's role:
if (value instanceof String message) {
System.out.println(message.trim());
}The expression being tested can also be more complex:
Object input = getInput();
if (input instanceof String) {
System.out.println("It is text");
}A pattern is useful when you need the value after the test. If you only need to know whether the type matches, an ordinary instanceof test is still clear.
Language level
Type patterns for instanceof became a permanent Java language feature in Java 16. Java 17 and later support them, so the examples require a current Java version such as Java 17, 21, or a later release.
Exercise
Rewrite this code using a type pattern: if (item instanceof Number) { Number number = (Number) item; System.out.println(number.intValue()); }
Show answer
if (item instanceof Number number) { System.out.println(number.intValue()); }