Pattern matching for instanceof
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Handling different kinds of payments means checking the type and then casting, every single time. That repeated cast is noisy and easy to get wrong.
The old way: check, then cast
Pattern matching tests a value's type or shape and, if it matches, binds it to a variable in one step, as in if (obj instanceof String s).
Before Java 16, using an object's real type took two steps: check it with obj instanceof String, then cast it with (String) obj to get a variable of that type.
Object value = "Pune";if (value instanceof String) { // 1. check the type String city = (String) value; // 2. cast to get a String variable System.out.println(city.length());}You need this when code receives an Object: a value read from a form, an item in a mixed list, the parameter of equals.
That means writing the type name three times: if (obj instanceof String) { String s = (String) obj; ... }. It is noisy, and it is easy to copy a block, change the check and forget to change the cast. The wrong cast compiles and then fails at run time with a ClassCastException.
instanceof is always false for null, so a passed check also proves the value is not null.Pattern variables (Java 16)
Java 16 lets you put a variable name right after the type: obj instanceof String s. This is a type pattern: a type test plus a variable. The variable s is called a pattern variable.
Example 1 · Old cast and new pattern, side by side
public class PatternBasicsDemo { static String describeOld(Object value) { if (value instanceof String) { String s = (String) value; return "text of length " + s.length(); } if (value instanceof Integer) { Integer n = (Integer) value; return "whole number, doubled " + (n * 2); } return "something else"; }
static String describeNew(Object value) { if (value instanceof String s) { return "text of length " + s.length(); } if (value instanceof Integer n) { return "whole number, doubled " + (n * 2); } return "something else"; }
public static void main(String[] args) { Object[] formValues = {"Ananya", 42, 7.5, null}; for (Object v : formValues) { System.out.println(describeOld(v) + " | " + describeNew(v)); } }}text of length 6 | text of length 6 whole number, doubled 84 | whole number, doubled 84 something else | something else something else | something else
What this code does
value instanceof String schecks the type and createssalready cast toString. Both methods give the same answers, but the new one has no cast lines.7.5is aDouble, so neither check matches.nullalso falls through:instanceofis alwaysfalsefornull, so a pattern variable is nevernull.
Example 2 · Payment fees from a mixed list
import java.util.List;
class UpiPayment { final String upiId; final int amount;
UpiPayment(String upiId, int amount) { this.upiId = upiId; this.amount = amount; }}
class CardPayment { final String last4; final int amount;
CardPayment(String last4, int amount) { this.last4 = last4; this.amount = amount; }}
class CashPayment { final int amount;
CashPayment(int amount) { this.amount = amount; }}
public class PaymentFeeDemo { static String receipt(Object payment) { if (payment instanceof UpiPayment upi) { return "UPI " + upi.upiId + ": Rs " + upi.amount + ", fee Rs 0"; } else if (payment instanceof CardPayment card) { int fee = card.amount * 2 / 100; return "Card *" + card.last4 + ": Rs " + card.amount + ", fee Rs " + fee; } else if (payment instanceof CashPayment cash) { return "Cash: Rs " + cash.amount + ", fee Rs 0"; } return "Unknown payment"; }
public static void main(String[] args) { List<Object> payments = List.of( new UpiPayment("ravi@okbank", 450), new CardPayment("4821", 1200), new CashPayment(80), "refund note"); for (Object p : payments) { System.out.println(receipt(p)); } }}UPI ravi@okbank: Rs 450, fee Rs 0 Card *4821: Rs 1200, fee Rs 24 Cash: Rs 80, fee Rs 0 Unknown payment
What this code does
- Each branch gets its own pattern variable (
upi,card,cash) of the exact class, so the fields can be read directly. A card payment pays a 2% fee. - This is the usual shape of a type-check chain. The Type patterns in switch lesson shows a shorter form of the same chain (Java 21).
Java creates it and assigns it only when the test is true.
The cast is now done by Java, so it can never disagree with the check. Inside if (amount instanceof Integer rupees), rupees is an Integer you can use directly: rupees * 100.
A pattern variable cannot reuse the name of a local variable that is already in scope; that is a compile error. Pick a short, clear name such as s, n or p.
- Old:
if (o instanceof Integer) { Integer n = (Integer) o; ... } - New:
if (o instanceof Integer n) { ... } - The check and the cast are one step, so they always match.
- Pattern matching for instanceof is standard from Java 16, so it works on Java 17.
Scope: where the pattern variable can be used
The scope of a variable is the part of the code where its name can be used. A pattern variable is in scope only where Java is sure the test was true.
if (o instanceof String s) { ... }:sis usable inside theifblock.if (o instanceof String s && !s.isBlank()):sis usable after&&and inside the block.if (o instanceof String s || s.isBlank()): compile error,smay not be assigned.if (!(o instanceof String s)) return;:sis usable on the lines after theif.if (!(o instanceof String s)) { ... } else { ... }:sis usable only in theelseblock.
Example 3 · Scope with && and with a negated check
public class PatternScopeDemo { static String checkName(Object input) { if (input instanceof String s && !s.isBlank()) { return "Name: " + s.trim(); } return "Name missing"; }
static String grade(Object input) { if (!(input instanceof Integer marks)) { return "Not a number"; } // marks is in scope here: the method returned above if the test failed if (marks >= 75) { return marks + " -> Distinction"; } return marks >= 35 ? marks + " -> Pass" : marks + " -> Fail"; }
public static void main(String[] args) { System.out.println(checkName(" Kiran ")); System.out.println(checkName(" ")); System.out.println(checkName(99)); System.out.println(grade(82)); System.out.println(grade(48)); System.out.println(grade(20)); System.out.println(grade("eighty")); }}Name: Kiran Name missing Name missing 82 -> Distinction 48 -> Pass 20 -> Fail Not a number
What this code does
- In
checkName,s.isBlank()runs only afterinstanceofwas true, sosis safe to use on the right of&&. - In
grade, the negated check returns early. Every line after thatifknowsinputis anInteger, somarksstays in scope for the rest of the method.
Example 4 · Mistake: using the pattern variable after ||
public class OrScopeErrorDemo { static boolean isShortText(Object o) { return o instanceof String s || s.length() < 5; }
public static void main(String[] args) { System.out.println(isShortText("Hi")); }}OrScopeErrorDemo.java:3: error: cannot find symbol
return o instanceof String s || s.length() < 5;
^
symbol: variable s
location: class OrScopeErrorDemo
1 errorWhat this code does
- The right side of
||runs only when the left side is false, that is, whenois not aString. At that pointshas no value, so Java does not let you use it. - The fix is
o instanceof String s && s.length() < 5. Read the condition aloud: "it is a String and that String is short".
With &&, the right side runs only when the left side is true, so o instanceof String s && s.length() > 3 is fine. With ||, the right side runs when the left side is false, so s is not assigned there and the compiler reports "cannot find symbol". A negated check works the other way round. After if (!(o instanceof String s)) { return; }, the rest of the method can use s: if the test had failed, the method would already have returned. This is a neat way to reject bad input at the top of a method.
Fix the error
Fix the pattern variable scope
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Print texts longer than 3 characters.
Error
Check.java:3: error: cannot find symbol
if (o instanceof String s || s.length() > 3) {
^
symbol: variable sRewriting an equals method
equals(Object o) is the classic place for check-then-cast. The old body needs an instanceof check, a cast into a new variable and then the field comparisons.
Example 5 · A shorter equals method
import java.util.ArrayList;import java.util.List;import java.util.Objects;
class Ticket { private final String pnr; private final int seat;
Ticket(String pnr, int seat) { this.pnr = pnr; this.seat = seat; }
@Override public boolean equals(Object o) { return o instanceof Ticket t && pnr.equals(t.pnr) && seat == t.seat; }
@Override public int hashCode() { return Objects.hash(pnr, seat); }}
public class TicketEqualsDemo { public static void main(String[] args) { Ticket booked = new Ticket("PNR4521", 32); Ticket scanned = new Ticket("PNR4521", 32); Ticket other = new Ticket("PNR4521", 33);
System.out.println("Same seat: " + booked.equals(scanned)); System.out.println("Other seat: " + booked.equals(other)); System.out.println("Compared with null: " + booked.equals(null)); System.out.println("Compared with text: " + booked.equals("PNR4521"));
List<Ticket> chart = new ArrayList<>(); chart.add(booked); System.out.println("Chart has scanned ticket: " + chart.contains(scanned)); }}Same seat: true Other seat: false Compared with null: false Compared with text: false Chart has scanned ticket: true
What this code does
- One expression does the type check, the cast and the field comparisons.
&&stops at the firstfalse, sonulland aStringboth returnfalsewithout any crash. t.pnrreads a private field of anotherTicket; that is allowed inside the same class.list.containscallsequals, so the scanned copy is found.
With a pattern, the whole method becomes one expression: return o instanceof Ticket t && pnr.equals(t.pnr) && seat == t.seat;. If o is null or not a Ticket, instanceof is false and && stops at once, so the method returns false safely. The pattern variable is new, so its name must not clash with a field. Keep hashCode in step: compare the same fields in both.
final, so code could assign a new value to it. Never do this; it makes the code hard to follow.Next step
Check your understanding
12 quick questions