Articles Java

Java switch pattern matching: practical examples

Pattern matching for switch lets a case label test the type of a value and bind it to a variable in one step, so a chain of instanceof checks and casts becomes a single switch. It is a standard feature since Java 21 (JEP 441) and needs no flags. Combined with a sealed interface, the compiler also checks that you handled every case.

All examples below use one small domain, the result of a payment attempt:

record Money(long cents, String currency) {}

sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String transactionId, Money amount) implements PaymentResult {}
record Declined(String reason, boolean retryable) implements PaymentResult {}
record Pending(String provider) implements PaymentResult {}

Java pattern matching switch example: before and after

The classic version tests, casts, and ends with a throw for the case nobody expects:

static String describe(Object result) {
    if (result instanceof Approved) {
        Approved approved = (Approved) result;
        return "Paid, transaction " + approved.transactionId();
    } else if (result instanceof Declined) {
        Declined declined = (Declined) result;
        return "Declined: " + declined.reason();
    } else if (result instanceof Pending) {
        return "Waiting for the provider";
    }
    throw new IllegalArgumentException("Unknown result: " + result);
}

With type patterns in a switch expression:

static String describe(PaymentResult result) {
    return switch (result) {
        case Approved approved -> "Paid, transaction " + approved.transactionId();
        case Declined declined -> "Declined: " + declined.reason();
        case Pending pending -> "Waiting for the provider";
    };
}

Each case is a type pattern: a type plus a variable that is in scope only in that branch, already cast. The casts are gone, and so is the throw at the end. The next sections explain why the compiler accepts a switch with no default.

How do guards with when work?

A guard adds a boolean condition to a pattern. The label matches only if the type matches and the condition is true:

static String nextStep(PaymentResult result) {
    return switch (result) {
        case Declined d when d.retryable() -> "Ask the customer to try again";
        case Declined d -> "Offer another payment method";
        case Approved a -> "Ship the order";
        case Pending p -> "Check again in a minute";
    };
}

Labels are tried from top to bottom, so the guarded label goes first and the plain Declined d catches the rest. A guarded label never counts towards exhaustiveness, because the compiler does not reason about what the condition covers. Delete the second line and the switch no longer compiles, even though the other two types are handled.

Do you need a default with a sealed interface?

No. A switch that uses patterns must be exhaustive, and with a sealed interface the compiler knows the full list of subtypes. Three permitted types and three unguarded labels means every value is covered.

That is the real benefit. Add a fourth result to the hierarchy:

sealed interface PaymentResult permits Approved, Declined, Pending, Refunded {}
record Refunded(String transactionId) implements PaymentResult {}

Every switch that does not handle Refunded now fails to compile:

Payments.java:11: error: the switch expression does not cover all possible input values
        return switch (result) {
               ^

Adding a default branch throws this away. The code keeps compiling, and the new subtype falls into a branch written before it existed. My advice: on a sealed hierarchy you own, leave default out and let the compiler list the places you have to update.

Record patterns and nested deconstruction

A record pattern (JEP 440, also final in Java 21) goes one step further than a type pattern: it takes the record apart and binds its components. Patterns nest, so you can reach into Money inside Approved without calling a single accessor:

static String receipt(PaymentResult result) {
    return switch (result) {
        case Approved(String id, Money(long cents, String currency)) when cents >= 100_000 ->
                "Large payment " + id + ": " + cents / 100 + " " + currency;
        case Approved(var id, Money(var cents, var currency)) ->
                "Payment " + id + ": " + cents / 100 + " " + currency;
        case Declined(String reason, boolean retryable) -> "No charge (" + reason + ")";
        case Pending(String provider) -> "Awaiting " + provider;
    };
}

For new Approved("tx-1002", new Money(250_000, "PLN")) this returns Large payment tx-1002: 2500 PLN. You can write the component types out or use var.

One trap: a record pattern never matches null. An Approved whose amount is null matches neither of the first two labels, and because the compiler considered the switch exhaustive, the failure arrives at run time as a java.lang.MatchException. If a component can be null, bind it with a type pattern instead (Approved(var id, var amount)) and check it yourself, or better, reject null in the record’s constructor.

How does switch handle null?

As it always did, unless you say otherwise: a null selector throws NullPointerException before any label is tried. A type pattern such as case Approved a does not match null. To handle it inside the switch, add an explicit label:

static String status(PaymentResult result) {
    return switch (result) {
        case null -> "No payment attempt yet";
        case Approved a -> "PAID";
        case Declined d -> "FAILED";
        case Pending p -> "PENDING";
    };
}

null can share a label only with default, written as case null, default ->. A plain default on its own still does not match null.

Dominance: compiler errors caused by label order

Since order matters, the compiler rejects a label that can never be reached. Put the unguarded Declined first and the guarded one below it:

case Declined d -> "Offer another payment method";
case Declined d when d.retryable() -> "Ask the customer to try again";
Payments.java:11: error: this case label is dominated by a preceding case label
            case Declined d when d.retryable() -> "Ask the customer to try again";
                 ^

The same error appears when a supertype comes before its subtype, for example case PaymentResult r above case Approved a. The rule to remember is specific before general: guarded labels before the unguarded label of the same type, subtypes before supertypes.

A related message shows up when a pattern that matches everything is combined with default:

Payments.java:29: error: switch has both an unconditional pattern and a default label

Both would catch all remaining values, so keep only one of them.

Unnamed patterns with _ (Java 22 and later)

Several branches above bind a variable they never use. Since Java 22 (JEP 456) you can write _ instead. It also allows more than one pattern in a single label, which is not permitted when the patterns declare named variables:

static boolean isFinal(PaymentResult result) {
    return switch (result) {
        case Approved _, Declined _ -> true;
        case Pending _ -> false;
    };
}

static String currencyOf(PaymentResult result) {
    return switch (result) {
        case Approved(_, Money(_, String currency)) -> currency;
        case Declined _, Pending _ -> "n/a";
    };
}

This works on Java 25 without flags. On Java 21 it does not compile; javac --release 21 answers unnamed variables are not supported in -source 21. Everything else shown so far compiles for Java 21.

What is still preview: primitive types in patterns

Patterns over primitive types are not final in Java 25. They are in their third preview there (JEP 507), and Java 26 carries a fourth (JEP 530). The feature lets you switch on long, float, double and boolean, and use primitive type patterns with guards:

// Preview feature in Java 25: compile and run with --enable-preview
static String riskBand(long cents) {
    return switch (cents) {
        case 0L -> "nothing to charge";
        case long c when c < 10_000 -> "low";
        case long c -> "needs review";
    };
}

Without the flag, JDK 25 refuses it:

Payments.java:3: error: primitive patterns are a preview feature and are disabled by default.
        return switch (cents) {
                      ^
  (use --enable-preview to enable primitive patterns)

Preview features can change between releases, so keep this out of production code for now. Note that a primitive nested in a record pattern, like long cents in Money(long cents, String currency), is fine on Java 21 as long as it is exactly the component’s declared type.

Summary

  • Pattern matching for switch is final since Java 21: type patterns, when guards, case null and record patterns all work without flags.
  • On a sealed hierarchy, skip default. A new subtype then becomes a compile error in every switch that has to change.
  • Order labels from specific to general. The compiler reports dominated labels, and guarded labels do not count towards exhaustiveness.
  • null throws NullPointerException unless there is a case null, and a nested record pattern that meets a null component ends in MatchException.
  • _ needs Java 22 or later. Primitive type patterns are still a preview feature in Java 25.