Stop 06 · Core Java APIsTopics · 8/8

Pattern Matching (instanceof & switch)

Part of the Java Roadmap

In short

Code that checks "what type is this?" used to be full of casts and long if-else chains. Modern Java lets you test a type, unpack its data and handle every case in one clear switch, with the compiler checking you didn't miss one.

Modern Java lets instanceof test a type and bind a variable in one step, and lets switch match on types and record patterns. This removes manual casts and makes type-based logic shorter and safer.

The jaadu sorts parcels of different shapes and sizes into matching slots on a tall wooden post office sorting rack.

Think of it like this

The post office sorting rack

At a Chennai post office, a sorter looks at each parcel's shape and drops it into the matching slot: letters here, small boxes there, heavy cartons in the corner. She even peeks at the label to send fragile ones to a special slot. Pattern matching is that sorter: it checks the type, opens the label and routes the object, all in one move.

Watch it happen

Checking a type, old and new

Before Java 16

  • if (o instanceof String) { String s = (String) o; ... }
  • Type written twice, plus a manual cast
  • Long if-else chains for each type
  • Easy to forget a case

Java 21

  • if (o instanceof String s) { ... }
  • Type test and variable in one step
  • switch with type and record patterns
  • Sealed types make the switch exhaustive

Use instanceof patterns for single checks and pattern switch when handling several types, especially sealed hierarchies.

The big ideas

What you need to know

instanceof binds a variable

o instanceof String s tests the type and gives you s already cast. You can combine it: o instanceof String s && !s.isBlank().

Type patterns in switch

case Upi u -> ... matches by type. The first matching case wins, so put specific cases before general ones.

Record patterns

case Card(String last4, long paise, boolean intl) unpacks a record's fields straight into variables (Java 21).

Guards and exhaustiveness

Add when conditions to refine a case. With a sealed interface, the compiler knows every subtype, so no default is needed.

How it works

How a pattern switch picks a case

  1. 1

    Evaluate

    Java evaluates the selector, here the Payment object.

  2. 2

    Test in order

    Each case pattern is tried from top to bottom against the object's runtime type.

  3. 3

    Check the guard

    If a case has a when condition, it must also be true for the case to match.

  4. 4

    Bind and run

    Matching variables are bound, already cast, and the arrow's expression runs.

See it in code

Walk through the code

java
1public class PaymentFees {2 3    sealed interface Payment permits Upi, Card, NetBanking {}4    record Upi(String vpa, long paise) implements Payment {}5    record Card(String last4, long paise, boolean international) implements Payment {}6    record NetBanking(String bank, long paise) implements Payment {}7 8    static long feePaise(Payment p) {9        return switch (p) {10            case Upi u -> 0;11            case Card(String last4, long paise, boolean intl) when intl -> paise * 3 / 100;12            case Card c -> c.paise() * 2 / 100;13            case NetBanking nb -> 1500;14        };15    }16 17    static String describe(Object o) {18        if (o instanceof String s && !s.isBlank()) {19            return "Text of length " + s.length();20        }21        return "Something else";22    }23 24    public static void main(String[] args) {25        System.out.println(feePaise(new Upi("ravi@okaxis", 50_000)));    // 026        System.out.println(feePaise(new Card("4321", 100_000, false)));  // 200027        System.out.println(feePaise(new Card("9876", 100_000, true)));   // 300028        System.out.println(describe("Chennai"));                         // Text of length 729    }30}

1/4A sealed interface with exactly three record types. The compiler knows the full list.

Made-up fee rules for a checkout, using a sealed interface, record patterns and a guard. Needs Java 21.

Save yourself the pain

Common mistakes

Oops

Putting case Card c before case Card(...) when intl.

Do this instead

Order matters. The general case would catch every card, so the compiler rejects the specific case as unreachable. Put specific cases first.

Oops

Adding a default branch to a switch over a sealed type.

Do this instead

Leave it out. Then adding a new Payment type later causes a compile error at every switch that needs updating.

Oops

Still writing String s = (String) o; after instanceof.

Do this instead

Use o instanceof String s and drop the manual cast.

Your mission

Shape area calculator

~25 min

Quick check

Why does a switch over a sealed interface not need a default branch?

Go deeper

  1. 1Rewrite an instanceof check plus cast using pattern matching for instanceof.
  2. 2Write a switch expression that returns a different description for each shape type.
  3. 3Use a record pattern to pull fields out of a record inside a switch case.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge