Pattern matching for switch in Java 21, with examples

Java 21 lets switch match on types, not just constants. Here is how it replaces the old if-instanceof-cast ladder, how when guards and case null work, the dominance and exhaustiveness rules, and how record patterns unpack data right in the case label.

Left, a tilted sheet labelled before, if-instanceof ladder: a chain of if obj instanceof Integer, String and Point checks, each followed by a cast highlighted in red. An arrow points to a yellow sheet labelled Java 21, one switch: return switch obj, with case null, case Integer i, case String s when s.isEmpty, case String s, case Point(int x, int y), and default.
Fig. 1 — The same logic, before and after. No casts, and the compiler checks the cases.

Every Java developer has written this ladder:

// The old way
if (obj instanceof Integer) {
    Integer i = (Integer) obj;
    result = "int " + i;
} else if (obj instanceof String) {
    String s = (String) obj;
    result = "string of length " + s.length();
} else {
    result = "unknown";
}

Check the type, cast to the same type, give it a new name, repeat. It’s noisy, and the compiler can’t tell you if you missed a case. Java 21 made pattern matching for switch (JEP 441) a standard feature, so the same logic becomes:

// Java 21
String result = switch (obj) {
    case Integer i -> "int " + i;
    case String s  -> "string of length " + s.length();
    default        -> "unknown";
};

This guide covers how it works, the rules that keep it safe, and how it combines with records and sealed classes.

How we got here

Pattern matching arrived in Java in small steps:

Java version Feature
Java 14 Switch expressions: case X -> arrows, switch that returns a value, yield
Java 16 Pattern matching for instanceof: if (obj instanceof String s)
Java 17 Sealed classes: closed type hierarchies
Java 21 Pattern matching for switch and record patterns

A quick refresher: switch expressions and instanceof patterns

The arrow form of switch (Java 14) doesn’t fall through, can list several labels in one case, and can return a value. Use yield to return from a block:

String kind = switch (day) {
    case "SAT", "SUN" -> "weekend";
    default -> {
        String lower = day.toLowerCase();
        yield "weekday (" + lower + ")";
    }
};

And since Java 16, instanceof can declare a variable when the check succeeds, and you can use it straight away in the same condition:

if (obj instanceof String s && s.length() > 3) {
    System.out.println(s.toUpperCase());   // s is already a String
}

Java 21 brings that same idea into switch.

Type patterns in switch

A type pattern in a case label checks the type and binds a variable:

// Java 21
static String describe(Object obj) {
    return switch (obj) {
        case Integer i    -> "int " + i;
        case String s     -> "string of length " + s.length();
        case List<?> list -> "list of " + list.size();
        default           -> "unknown: " + obj.getClass().getSimpleName();
    };
}

describe(42);            // "int 42"
describe("abc");         // "string of length 3"
describe(List.of(1, 2)); // "list of 2"
describe(3.5);           // "unknown: Double"

You can switch on any reference type now, not only int, String and enums.

Guards with when

Add a condition to a case with when. The case matches only if the type matches and the condition is true:

// Java 21
static String size(Object obj) {
    return switch (obj) {
        case String s when s.isEmpty()     -> "empty string";
        case String s when s.length() < 10 -> "short string";
        case String s                      -> "long string";
        case Integer i when i > 1000       -> "big number";
        case Integer i                     -> "small number";
        default                            -> "something else";
    };
}

Cases are tried top to bottom, so put the most specific guards first.

Handling null with case null

A traditional switch throws NullPointerException when given null. Java 21 still does that by default, for compatibility, but you can now handle null as a case:

return switch (obj) {
    case null      -> "nothing here";
    case String s  -> "text: " + s;
    default        -> "other";
};

You can also combine it with default: case null, default -> "other or nothing";.

Record patterns: unpack data in the case label

Record patterns (JEP 440, also final in Java 21) let a case match a record and pull out its components at the same time. They nest, and var works inside them:

// Java 21
record Point(int x, int y) {}
sealed interface Shape permits Circle, Rect {}
record Circle(Point center, int radius) implements Shape {}
record Rect(Point topLeft, Point bottomRight) implements Shape {}

static String where(Shape shape) {
    return switch (shape) {
        case Circle(Point(var x, var y), int r) when r > 100 -> "big circle at " + x + "," + y;
        case Circle(Point(var x, var y), int r)              -> "circle at " + x + "," + y;
        case Rect(Point topLeft, Point bottomRight)          -> "rect from " + topLeft + " to " + bottomRight;
    };
}

One case label checks that the shape is a Circle, takes out its centre, checks that the centre is a Point, and binds x, y and r. No casts, no accessor calls.

“A record pattern reads like the constructor call that built the object, run in reverse.”

Exhaustiveness: the compiler checks every case

A switch expression (one that returns a value) must cover every possible input. Switching over Object, that means you need a default:

return switch (obj) {
    case String s -> "text";
};   // error: the switch expression does not cover all possible input values

Over a sealed type, you don’t need default: if every permitted subtype has a case, the switch is complete. That’s what makes the where method above compile without one. And when someone adds a new Triangle to the sealed interface, every switch that doesn’t handle it stops compiling. That’s the biggest win of the whole feature: missing cases become compile errors.

The same goes for enums. A switch expression that lists every constant needs no default:

enum Status { ACTIVE, SUSPENDED, CLOSED }

int fee = switch (status) {
    case ACTIVE    -> 0;
    case SUSPENDED -> 100;
    case CLOSED    -> 500;
};

Dominance: more specific cases first

If an earlier case already matches everything a later case would, the later case can never run, and the compiler rejects it:

return switch (obj) {
    case CharSequence cs -> "char sequence";
    case String s        -> "string";   // error: this case label is dominated by a preceding case label
    default              -> "other";
};

String is a CharSequence, so the second case is unreachable. Put the narrower type (or the guarded case) first.

When to use pattern matching for switch

Good fits:

  • Handling the different subtypes of a sealed interface: payments, events, commands, API results.
  • Processing messages or JSON nodes of several known types.
  • Replacing long if-else instanceof ladders.

Think twice:

  • If the behaviour belongs to the type, a plain polymorphic method (shape.area()) might be simpler than a switch outside it. Pattern matching shines when the operation lives outside the types: in a separate service, a formatter, a serializer.
  • Switching over Object with a default loses exhaustiveness checking. Prefer a sealed type when you control the hierarchy.

What came after Java 21

  • Unnamed patterns (_), final in Java 22, let you skip parts you don’t need: case Circle(Point(var x, var y), _).
  • Primitive types in patterns (case int i when i > 0) have been in preview since Java 23.

Key takeaways

  • Java 21 made pattern matching for switch and record patterns standard features.
  • A type pattern (case String s) checks the type and binds a variable, with no cast.
  • when guards add conditions; cases are tried top to bottom.
  • case null handles null explicitly; without it, null still throws.
  • Record patterns unpack records in the case label, and they nest.
  • Over a sealed type or an enum, the compiler checks the switch is exhaustive; dominated cases are compile errors.

Frequently asked questions

What is pattern matching for switch in Java?

A Java 21 feature that lets switch cases match on an object’s type (and on a record’s contents), binding a typed variable for use in that case. It replaces chains of instanceof checks and casts.

Which Java version has pattern matching for switch?

It was previewed in Java 17 through 20 and became standard in Java 21 (JEP 441).

What does when mean in a Java switch?

when adds a guard to a pattern case. case String s when s.isEmpty() matches only strings that are empty.

Can a Java switch handle null?

Yes, from Java 21, with case null. Without it, a switch still throws NullPointerException for a null input.

What is a record pattern in Java?

A pattern that matches a record and extracts its components, such as case Point(int x, int y). Record patterns can be nested and used with instanceof and switch.

Next in Modern Java: sequenced collections, Java 21’s answer to “how do I get the last element?”.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.