Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 14 / Topic 2 of 7

Pattern matching for instanceof (JEP 394)

Pattern matching for instanceof (finalized in Java 16) tests the type and declares a narrowed, already-cast variable in the same expression. method instanceof Upi upi means: if method is a Upi, continue with upi already typed as Upi — no second line, no separate cast. Think of a security check that hands you a correctly-labeled visitor badge the moment it confirms who you are, instead of waving you through and making you fill out your own badge afterwards.

// before Java 16: test, then cast, as two separate steps
if (method instanceof Upi) {
    Upi upi = (Upi) method;
    return "UPI: " + upi.vpa();
}

// Java 16+: test and bind in one step
if (method instanceof Upi upi) {
    return "UPI: " + upi.vpa();
}

A guarded pattern adds a && condition that can use the bound variable directly; the whole expression — pattern and guard — has to be true for the branch to run:

if (method instanceof Card card && card.last4Digits().equals("0000")) {
    return "SUSPICIOUS: " + card.network() + " card ending 0000";
}

The bound variable's scope follows normal flow analysis, not just "inside these braces" — it is in scope anywhere the compiler can prove the instanceof was true, including after a negated check returns early:

static int cardDigitSum(Object maybeCard) {
    if (!(maybeCard instanceof Card card)) {
        return -1;                     // card is NOT in scope here
    }
    return card.last4Digits().chars().map(c -> c - '0').sum();   // card IS in scope here
}
$ javac InstanceofPatternDemo.java
$ java InstanceofPatternDemo
-- old style (test, then cast) --
UPI: ravi.kumar@upi
RuPay card ending 4321
net banking: SBI

-- pattern matching instanceof (JEP 394) --
UPI: ravi.kumar@upi
RuPay card ending 4321
net banking: SBI

-- guarded patterns --
looks fine
SUSPICIOUS: Visa card ending 0000
SUSPICIOUS: malformed VPA not-a-vpa

-- negated pattern, variable scoped to the rest of the method --
card digit sum: 10
not a card: -1

⚠️ A pattern variable still shadows like any other local. Reusing an existing name for the pattern variable (card when a card of a different type already exists in scope) is a compile error, not a silent shadowing bug — the compiler catches it immediately.

Full program: examples/InstanceofPatternDemo.java.

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide