Java Pattern Matching with instanceof and switch
p instanceof Card c replaces a test, a cast and a variable. c is usable after && but not after ||, a switch over Object needs a default for "gift-note", and when guards send Cash 150 to an ID check while Cash 40 drops to the plain case.
What you will learn
- Test, cast and name an object in one step with instanceof Card c
- Use the pattern variable inside the same && condition
- Write a switch with one case per type, and a default for an open type
- Add conditions with when and order cases so a guarded case can run
Before you start
- Java sealed classes and interfaces
- Java if, else and switch
Pattern matching is a simple idea: test the type of an object, give it a name, and send it the right way. These examples use the sealed Payment family of Card, Wallet and Cash from sealed classes.
Test, cast and name in one step
// Old way: test, then cast by hand, then name it
static String oldWay(Payment p) {
if (p instanceof Card) {
Card c = (Card) p;
return c.holder() + " paid " + c.amount() + " by card";
}
return "not a card";
}
// Pattern: test, cast and name it in one step
static String newWay(Payment p) {
if (p instanceof Card c) {
return c.holder() + " paid " + c.amount() + " by card";
}
return "not a card";
}
Emma Clarke paid 250.0 by card
Emma Clarke paid 250.0 by card
The old way takes three steps: instanceof to test, a cast, then a variable, and the word Card keeps repeating. p instanceof Card c does all three: the same object goes in and comes out as a Card named c, usable wherever the test was true. Same output, shorter code. A hand cast to the wrong type, (Wallet) first, compiles but throws ClassCastException at run time.
Use c in the same condition
// c exists only where the test is true, so && can use it straight away
static boolean needsIdCheck(Payment p) {
return p instanceof Cash c && c.amount() > 100;
}
List<Payment> today = List.of(
new Card("Emma Clarke", 250.0),
new Wallet("liam.w@wallet", 80.0),
new Cash(40.0),
new Cash(150.0));
for (Payment p : today) {
if (needsIdCheck(p)) {
System.out.println("ID check: " + p);
}
}
ID check: Cash[amount=150.0]
On the right of &&, c already exists, because you only get there when p really is a Cash. Cash 40 is a Cash but not over 100. Change && to || and it won't compile: behind an "or", the test may have failed, so there's no c.
One case for each type
// Object is an open type: anything can arrive, so the switch needs a default
static String label(Object o) {
return switch (o) {
case Card c -> "Card of " + c.holder();
case Wallet w -> "Wallet " + w.walletId();
case Cash c -> "Cash " + c.amount();
default -> "Not a payment: " + o;
};
}
Card of Emma Clarke
Wallet liam.w@wallet
Cash 40.0
Not a payment: gift-note
The inbox is a List<Object>, so anything can go in, including the String "gift-note". Each case is a type pattern: case Card c means "if it's a Card, call it c". The String matches none, so default catches it. Object is open, so the switch needs a default; delete it and javac says the switch doesn't cover every Object. A switch over the sealed Payment is closed and needs none.
Add a condition with when
// Cases are tried top to bottom; "when" adds a condition to a case
static String screen(Payment p) {
return switch (p) {
case Cash c when c.amount() > 100 -> "ID check for cash " + c.amount();
case Cash c -> "Cash " + c.amount() + " accepted";
case Card c when c.amount() > 200 -> "PIN needed: " + c.holder();
case Card c -> "Tap: " + c.holder();
case Wallet w -> "Wallet " + w.walletId() + " accepted";
};
}
PIN needed: Emma Clarke
Wallet liam.w@wallet accepted
Cash 40.0 accepted
ID check for cash 150.0
when adds a condition, called a guard. The Card is 250, over 200, so it lands in the guarded Card case. The Wallet has no condition. Cash 40 fails the first guard and the plain Cash case takes it; Cash 150 passes it. Cases are tried top to bottom, so swap the two Cash cases and the plain one takes every Cash. Javac refuses with this case label is dominated by a preceding case label. Put the guarded case first.
Recap
| You write | Compiles? |
|---|---|
p instanceof Cash c && c.amount() > 100 | yes: c exists after && |
p instanceof Cash c || c.amount() > 100 | no: there's no c behind || |
plain case Cash c above the guarded one | no: the guarded case can never run |
| guarded case first, plain case after | yes |
| switch over Object with no default | no: an open type needs a default |
Next, patterns that unpack a record's components in one go: record patterns.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
