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

Part 14 / Topic 3 of 7

Pattern matching for switch (JEP 441)

Pattern matching for switch (finalized in Java 21) brings the same instanceof-style type patterns into a switch, adds a when clause for guards, and lets case null be written explicitly instead of throwing NullPointerException the moment a switch subject is null. Think of a sorting counter at a courier hub: each parcel's shape decides which conveyor belt it goes to, a guard is a second check once you already know the shape ("is this envelope also marked urgent?"), and an empty parcel gets its own, explicitly handled bin instead of jamming the belt.

sealed interface IrctcTicketStatus permits Confirmed, Waitlisted, RacStatus, Cancelled {}
record Confirmed(String coach, String seat) implements IrctcTicketStatus {}
record Waitlisted(int position) implements IrctcTicketStatus {}
record RacStatus(int racNumber) implements IrctcTicketStatus {}
record Cancelled(String reason) implements IrctcTicketStatus {}

static String passengerMessage(IrctcTicketStatus status) {
    return switch (status) {
        case Confirmed c -> "Confirmed: coach " + c.coach() + ", seat " + c.seat();
        case Waitlisted w when w.position() <= 10 -> "Waitlisted #" + w.position() + ": likely to confirm";
        case Waitlisted w -> "Waitlisted #" + w.position() + ": unlikely to confirm";
        case RacStatus r -> "RAC " + r.racNumber() + ": shared berth until confirmed";
        case Cancelled c -> "Cancelled: " + c.reason();
    };
}

No default branch, and it still compiles — IrctcTicketStatus permits exactly these four types, every one is handled, so the compiler can prove the switch is exhaustive. Add a fifth permitted type later and this switch (and every other switch over IrctcTicketStatus in the codebase) stops compiling until the new case is handled too.

when is a guard: a boolean condition checked only after the pattern itself matches, using the pattern's bound variable. The two Waitlisted cases above are checked top to bottom, like any switch — the guarded one first, the unconditional fallback for that same type second.

Pattern matching also works switching on a plain Object, where case null is now a real, orderable case instead of a guaranteed NullPointerException:

static String classify(Object value) {
    return switch (value) {
        case null -> "no value supplied";
        case Integer i when i < 0 -> "negative amount: " + i;
        case Integer i -> "amount in rupees: " + i;
        case String s when s.startsWith("PNR-") -> "PNR reference: " + s;
        case String s -> "plain text: '" + s + "'";
        default -> "unhandled type: " + value.getClass().getSimpleName();
    };
}
$ javac SwitchPatternMatchingDemo.java
$ java SwitchPatternMatchingDemo
-- passenger-facing status messages --
Confirmed: coach B4, seat 22
Waitlisted #4: likely to confirm
Waitlisted #87: unlikely to confirm
RAC 12: shared berth until confirmed
Cancelled: train cancelled due to fog

-- classify(Object), including case null --
no value supplied
negative amount: -500
amount in rupees: 1200
PNR reference: PNR-4821093456
plain text: 'hello'
unhandled type: Double

⚠️ default is still required the moment the subject isn't a sealed, fully-covered type. switch (value) over Object above needs default, because Object has no closed set of subtypes the compiler can verify — only a switch over a sealed type (or an enum, as before) can be exhaustive without one.

Full program: examples/SwitchPatternMatchingDemo.java.

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

Search the guide