Pattern Matching for instanceof (Standard Since Java 16)
Pattern matching for instanceof combines a type test and a cast. obj instanceof String s checks the type and, if it matches, creates the variable s with the right type. It was previewed in Java 14 and 15 and became standard in Java 16 (JEP 394), so it is part of Java 17 LTS.
This tutorial explains the syntax, the flow-sensitive scope of the binding variable, and typical uses such as equals methods.
1. Why Is This Feature Useful?
The classic idiom repeats the type three times: if (o instanceof Money) { Money m = (Money) o; ... }. The cast is noise, and copy-paste errors can cast to the wrong type. A type pattern removes the cast and makes the code shorter and safer.
2. Syntax and Scope Rules
if (obj instanceof String s) { // s is in scope only where the test is true
System.out.println(s.length());
}
if (obj instanceof String s && !s.isBlank()) { ... } // usable after &&
if (!(obj instanceof String s)) {
return; // s is in scope after this early return
}
System.out.println(s.toUpperCase());
3. Practical Examples
Example 1: A concise equals() method
import java.util.Objects;
public class PatternEquals {
static final class Money {
private final long paise;
private final String currency;
Money(long paise, String currency) {
this.paise = paise;
this.currency = currency;
}
// Classic equals() becomes one readable expression
@Override
public boolean equals(Object o) {
return o instanceof Money other
&& paise == other.paise
&& currency.equals(other.currency);
}
@Override
public int hashCode() {
return Objects.hash(paise, currency);
}
}
public static void main(String[] args) {
Money a = new Money(9950, "INR");
System.out.println(a.equals(new Money(9950, "INR")));
System.out.println(a.equals(new Money(9950, "USD")));
System.out.println(a.equals("9950 INR"));
}
}
true false false
Example 2: Scope with && and negation
public class PatternScope {
static String classify(Object input) {
// Negated test with early return: s is in scope after the if
if (!(input instanceof String s)) {
return "not text";
}
if (s.isBlank()) {
return "blank text";
}
return "text with " + s.strip().split("\\s+").length + " word(s)";
}
static double total(Object amount) {
// The binding variable can be used in the rest of the && condition
if (amount instanceof Double d && d > 0) {
return d;
}
if (amount instanceof Integer i && i > 0) {
return i.doubleValue();
}
return 0;
}
public static void main(String[] args) {
System.out.println(classify(" pay the rent "));
System.out.println(classify(" "));
System.out.println(classify(42));
System.out.println(total(99.5) + total(10) + total(-5) + total("x"));
}
}
text with 3 word(s) blank text not text 109.5
The compiler tracks where the match is definitely true. That is why s is usable after the negated test returns, and why d > 0 may appear after &&.
4. Before and After
5. Important Points and Best Practices
- The binding variable cannot be used after
||, because the match may have failed. - A pattern whose type is the same as the expression's static type was a compile error up to Java 20; Java 21 allows it.
null instanceof String sisfalse, so the binding is nevernull.- For many types, a pattern
switch(final in Java 21) is clearer than a longif-elsechain.
6. Summary
- Type patterns for
instanceofbecame standard in Java 16 (JEP 394). obj instanceof T ttests, casts and declarestin one step.- The variable's scope follows where the match is definitely true.
- It simplifies
equalsmethods and type-dependent logic.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What is pattern matching for instanceof?
A Java feature, final since Java 16, that lets instanceof declare a variable of the tested type, for example o instanceof String s, removing the need for a cast.
Q2. Can the pattern variable be used outside the if block?
Yes, when the compiler can prove the match succeeded, for example after if (!(o instanceof String s)) return;.
Q3. Can I use the variable after ||?
No. With || the match may have failed, so the variable is not in scope.
Q4. Is the binding variable final?
No, it can be reassigned, but doing so is discouraged because it makes code harder to read.