00:00

Pattern Matching for instanceof (Standard Since Java 16)

Last updated: · 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

Syntax.java
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

PatternEquals.java
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"));
    }
}
Output
true
false
false

Example 2: Scope with && and negation

PatternScope.java
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"));
    }
}
Output
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

Type test, cast and variable in one step Before Java 16 an instanceof test was followed by a separate cast and variable declaration. A type pattern does all three in one expression. BEFORE instanceof Money type test (Money) o explicit cast Money m = ... new variable AFTER o instanceof Money m test + cast + variable
Figure 1: The pattern removes the repeated type and the unchecked cast.

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 s is false, so the binding is never null.
  • For many types, a pattern switch (final in Java 21) is clearer than a long if-else chain.

6. Summary

  • Type patterns for instanceof became standard in Java 16 (JEP 394).
  • obj instanceof T t tests, casts and declares t in one step.
  • The variable's scope follows where the match is definitely true.
  • It simplifies equals methods and type-dependent logic.

Related Tutorials

7. References