Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

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
Four payments on the left, five cases on the right in code order. Card 250 goes to Card when amount over 200: PIN needed. Wallet goes to the Wallet case. Cash 40 fails the guard on the first Cash case and falls to the plain Cash case. Cash 150 fits the first, guarded Cash case: ID check. Card 250Wallet 80Cash 40Cash 150 1 Cash c when amount > 1002 Cash c 3 Card c when amount > 2004 Card c 5 Wallet w Cash 40 skips case 1: 40 is not over 100
Each payment goes to the first case that fits, from the top.

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 writeCompiles?
p instanceof Cash c && c.amount() > 100yes: c exists after &&
p instanceof Cash c || c.amount() > 100no: there's no c behind ||
plain case Cash c above the guarded oneno: the guarded case can never run
guarded case first, plain case afteryes
switch over Object with no defaultno: an open type needs a default

Next, patterns that unpack a record's components in one go: record patterns.

Keep going in Java · 43 of 79

Previous
Java Sealed Classes and Interfaces
Next post
Java Record Patterns: Unpacking a Record
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Test, cast and name in one step
  • Use c in the same condition
  • One case for each type
  • Add a condition with when
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.