Records, Sealed, Immutable Classes ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-12-04

Java Pattern Matching for switch: Type Patterns, Record Patterns and when

Pattern matching for switch is a Java feature in which a case label tests not a value but the “shape” of an object — its type or its record structure — and declares variables of the right type at the same time. Instead of a chain of if (o instanceof A a) ... else if (o instanceof B b) ... you write one switch with the labels case A a -> and case B b ->. Patterns in switch became standard in Java 21: JEP 441 (pattern matching for switch) and JEP 440 (record patterns).

The most surprising part of the feature is that label order now matters to the compiler. Swap two branches and the code stops compiling:

// DominanceDemo.java
public class DominanceDemo {
    static String describe(Object o) {
        return switch (o) {
            case CharSequence cs -> "text of length " + cs.length();
            case String s -> "string " + s;          // compile error
            default -> "something else";
        };
    }

    public static void main(String[] args) {
        System.out.println(describe("Java"));
    }
}
// error: this case label is dominated by a preceding case label

Every String is a CharSequence, so execution can never reach the second branch, and javac treats that as an error rather than dead code. All the ordering rules are collected in Label order and dominance.

From an if-instanceof chain to switch

Pattern matching for switch replaces a chain of instanceof checks: each case Type name branch tests the type, casts to it and declares a variable in one step. The code gets shorter, and the compiler also checks the order of the branches and makes sure no variant is forgotten.

The idea comes from instanceof: Java 16 introduced if (obj instanceof String s), covered in Upcasting and Downcasting in Java. A switch simply lets you list several such checks in one place:

// IfChainVsSwitch.java
public class IfChainVsSwitch {
    static String formatOld(Object o) {
        if (o instanceof Integer i) {
            return "int " + i;
        } else if (o instanceof Long l) {
            return "long " + l;
        } else if (o instanceof String s) {
            return "string \"" + s + "\"";
        } else {
            return "other: " + o;
        }
    }

    static String formatNew(Object o) {
        return switch (o) {
            case Integer i -> "int " + i;
            case Long l    -> "long " + l;
            case String s  -> "string \"" + s + "\"";
            default        -> "other: " + o;
        };
    }

    public static void main(String[] args) {
        for (Object o : new Object[]{42, 7L, "Java", 3.14}) {
            System.out.println(formatOld(o) + " | " + formatNew(o));
        }
    }
}

Output:

int 42 | int 42
long 7 | long 7
string "Java" | string "Java"
other: 3.14 | other: 3.14

The result is the same, but the switch version has two advantages. If you put the checks of an if chain in the wrong order, nobody notices, while the switch refuses to compile. And if the selector is a sealed type, the compiler tells you which variant you forgot.

The labels you can write in a modern switch:

Label kind Example When it matches Since
Constant case 1, 2 ->, case "yes" ->, case RED -> The value equals the constant Java 1.0 (String since 7, comma lists since 14)
Type pattern case String s -> The object is an instance of the type (not null) Java 21
Record pattern case Point(int x, int y) -> The object is this record and its components match the nested patterns Java 21
Guarded pattern case Integer i when i > 0 -> The pattern matches and the condition is true Java 21
case null case null -> The selector is null Java 21
default default -> Nothing else matched (but not null) Java 1.0
case null, default case null, default -> Everything else, including null Java 21

The arrow syntax, yield and the difference between a switch statement and a switch expression are covered in Switch-Case Statement in Java. This lesson is only about patterns.

Type patterns: switch on type

A type pattern is a label of the form case Type name: it matches when the selector is not null and is an instance of the given type. The selector can be of any reference type — Object, an interface, an abstract class, an array. A switch with patterns, statement or expression, must be exhaustive.

// TypePatterns.java
import java.util.List;

public class TypePatterns {
    static void print(Object o) {
        switch (o) {
            case String s     -> System.out.println("String, length " + s.length());
            case List<?> list -> System.out.println("List, size " + list.size());
            case int[] arr    -> System.out.println("int[], length " + arr.length);
            default           -> System.out.println("Other: " + o.getClass().getSimpleName());
        }
    }

    public static void main(String[] args) {
        print("abc");
        print(List.of(1, 2, 3));
        print(new int[5]);
        print(3.5);
    }
}

Output:

String, length 3
List, size 3
int[], length 5
Other: Double

A pattern variable (s, list, arr) is visible only in its own branch. Referring to it in another branch or after the switch gives cannot find symbol. That is not an arbitrary rule: in any other branch the object is known to be of a different type, so the variable would have nothing to hold.

You can't test a type argument in a pattern. Because of erasure, the JVM doesn't know whether it has a List<String> or a List<Integer>, which is why the example uses List<?>. More on erasure in Java Generics.

Exhaustiveness: default is required

A classic switch over an int or a String didn't have to cover every value. A switch over patterns does — even a statement, not just an expression:

// NotExhaustive.java
public class NotExhaustive {
    static void print(Object o) {
        switch (o) {
            case String s  -> System.out.println("string " + s);
            case Integer i -> System.out.println("number " + i);
        }
    }

    public static void main(String[] args) {
        print("x");
    }
}
// error: the switch statement does not cover all possible input values

For a switch expression the message is the same, with expression instead of statement. There are three fixes: add default, add the unconditional pattern case Object o as the last branch, or make the selector a sealed type and list every variant — how that works is shown in Sealed types and pattern matching.

One more restriction: a type pattern doesn't work with a primitive selector. switch (x) over an int with the label case Integer i doesn't compile on Java 21–27 without flags:

// PrimitiveSelector.java
public class PrimitiveSelector {
    public static void main(String[] args) {
        int x = 5;
        switch (x) {
            case Integer i -> System.out.println(i);
        }
    }
}
// error: primitive patterns are a preview feature and are disabled by default.

The error text hints that this is changing: primitive type patterns are currently in preview, see What's next.

Guarded patterns: the when clause

A guarded pattern is a label of the form case Type name when condition ->. The branch runs only if the pattern matches and the boolean expression after when evaluates to true; otherwise matching continues with the next labels. The pattern variable is available inside the condition.

// GuardDemo.java
public class GuardDemo {
    static String classify(Object o) {
        return switch (o) {
            case Integer i when i < 0   -> "negative";
            case Integer i when i == 0  -> "zero";
            case Integer i              -> "positive";
            case String s when s.isBlank() -> "blank string";
            case String s               -> "string: " + s;
            default                     -> "other";
        };
    }

    public static void main(String[] args) {
        for (Object o : new Object[]{-5, 0, 17, "  ", "Java", 2.0}) {
            System.out.println(o + " -> " + classify(o));
        }
    }
}

Output:

-5 -> negative
0 -> zero
17 -> positive
   -> blank string
Java -> string: Java
2.0 -> other

The condition is evaluated only after the type has matched, so calling s.isBlank() inside when is safe: s is guaranteed to be a non-null String there. Guarded branches are checked top to bottom, so the narrower condition goes first. The unguarded branch of the same type comes last — put it first and you get a dominance error (see the next section).

The compiler doesn't analyze what's inside when. The three branches case Integer i when i < 0, when i == 0 and when i > 0 cover every number mathematically, but they don't count toward exhaustiveness — you still need an unguarded case Integer i or default. More in Sealed types and pattern matching.

Local variables used in when but declared outside it must be final or effectively final, just like in lambdas. Otherwise javac reports local variables referenced from a guard must be final or effectively final.

when is a contextual keyword, like yield or record: it has a special meaning only in a case label. Old code with a variable named when still compiles, and you can even use that variable in the guard itself:

// WhenAsName.java
public class WhenAsName {
    public static void main(String[] args) {
        int when = 5;
        Object o = 10;
        String r = switch (o) {
            case Integer i when i > when -> "big";
            default -> "small";
        };
        System.out.println(r + " " + when);
    }
}
// Output: big 5

In the Java 17 and 18 previews the condition was written with &&: case String s && s.length() > 3. Java 19 (JEP 427) replaced that syntax with when, so older articles show both forms; in Java 21+ only when works.

No side effects in when

A when condition can run for an object whose branch then doesn't fire: case Order o when audit.log(o) && o.isPaid() logs every order, including unpaid ones that fall through to the next branch. How many times and for which objects guards are evaluated depends on the order of the labels, not on your program logic. Keep only pure checks in when and put actions in the branch body.

Label order and dominance

Dominance is the rule that a label can't come after another label that already matches all of its values. If a branch can never run, javac reports this case label is dominated by a preceding case label. The general principle follows from that: go from specific to general — subtypes above supertypes, guarded branches above unguarded ones, constants above patterns.

Label order Result Why
case CharSequence cs, then case String s error: this case label is dominated by a preceding case label Every string is a CharSequence, the second branch is unreachable
case String s, then case CharSequence cs Compiles Subtype above supertype
case Integer i, then case Integer i when i > 0 error: this case label is dominated by a preceding case label The unconditional pattern takes every Integer
case Integer i when i > 0, then case Integer i Compiles A guarded pattern dominates nothing
case Integer i, then case 42 Error: this case label is dominated by a preceding case label A constant after an unconditional pattern of its type is unreachable
case 42, then case Integer i Compiles Constant above the pattern
default, then case String s error: this case label is dominated by a preceding case label Patterns after default are not allowed
default, then case 1 (switch over int) Compiles The old rule is kept for constants, for backward compatibility
case Object o and default in one switch error: switch has both an unconditional pattern and a default label Both catch “everything else”, one of them is redundant

The compiler compares only types and never looks into when conditions. So a guarded pattern doesn't dominate a constant, even when the guard obviously covers it. What does this code print?

// GuardBeforeConstant.java
public class GuardBeforeConstant {
    static String check(Integer n) {
        return switch (n) {
            case Integer i when i > 0 -> "positive " + i;
            case 42                   -> "the answer to the ultimate question";
            case Integer i            -> "not greater than zero: " + i;
        };
    }

    public static void main(String[] args) {
        System.out.println(check(42));
        System.out.println(check(-1));
    }
}

Output:

positive 42
not greater than zero: -1

The code compiles, but case 42 never fires: 42 is positive, and the first branch takes it. No error, no warning. In code review the easiest way to catch this is the rule “constants always go above patterns of their type”.

null in switch: case null and case null, default

A switch still throws NullPointerException when the selector is null and there is no case null label. That applies to switches with patterns too: neither default nor the unconditional case Object o catches null. The only way to handle it is explicitly — a separate case null branch or the combined case null, default.

// NullInSwitch.java
public class NullInSwitch {
    static String withNullCase(Object o) {
        return switch (o) {
            case null     -> "null";
            case String s -> "string " + s;
            default       -> "other";
        };
    }

    static String answer(String s) {
        return switch (s) {
            case "yes"          -> "confirmed";
            case null, default  -> "not confirmed";
        };
    }

    static String total(Object o) {
        return switch (o) {
            case Object x -> "object " + x;
        };
    }

    public static void main(String[] args) {
        System.out.println(withNullCase(null));
        System.out.println(withNullCase("Java"));
        System.out.println(answer(null));
        System.out.println(answer("yes"));
        try {
            System.out.println(total(null));
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }
    }
}

Output:

null
string Java
not confirmed
confirmed
NullPointerException

The total() method shows the case people get wrong most often: case Object x matches any object, but null is not an object, and the switch fails before it even checks the labels. This is deliberate, for compatibility: millions of lines of old code expect a switch on null to throw NPE, and the language chose not to silently route null into default.

case null has its own restrictions. It can be combined with a comma only with default — case null, String s doesn't compile. And a switch statement that contains case null becomes a “new” switch and must be exhaustive too, even if the selector is a plain String.

Record patterns in switch: deconstruction and nesting

A record pattern is a pattern such as case Point(int x, int y) that checks the object is that record and immediately breaks it into its components. The basic case is covered in Java Records; this section covers what makes record patterns really useful: nesting, var, generic records and checking combinations.

Nested record patterns and var

A component position can hold another pattern — a type pattern, a record pattern or var. That way one label takes apart an object of any depth:

// NestedRecordPatterns.java
record Point(int x, int y) { }
record Line(Point start, Point end) { }

public class NestedRecordPatterns {
    static String describe(Object o) {
        return switch (o) {
            case Line(Point(var x1, var y1), Point(var x2, var y2)) when x1 == x2 ->
                    "vertical line x=" + x1;
            case Line(Point(var x1, var y1), Point p2) ->
                    "line from (" + x1 + "," + y1 + ") to " + p2;
            case Point(int x, int y) -> "point " + x + "," + y;
            default -> "other";
        };
    }

    public static void main(String[] args) {
        System.out.println(describe(new Line(new Point(1, 2), new Point(1, 8))));
        System.out.println(describe(new Line(new Point(0, 0), new Point(3, 4))));
        System.out.println(describe(new Point(5, 6)));
        System.out.println(describe("abc"));
    }
}

Output:

vertical line x=1
line from (0,0) to Point[x=3, y=4]
point 5,6
other

var in a component means “the component type as declared in the record”: x1 here is an int. It's handy with long type names, but the reader no longer sees the component type in the label, so for short types the explicit form is usually clearer. A record pattern never matches null: if the start component of a Line is null, the nested Point(var x1, var y1) won't match.

Generic records and a null component

For a generic record you can omit the type argument in the pattern — the compiler infers it from the selector type. The more interesting part: a nested type pattern that is unconditional for the component type matches null as well.

// GenericRecordPattern.java
record Box<T>(T value) { }

public class GenericRecordPattern {
    static String unpack(Box<String> b) {
        return switch (b) {
            case Box(String s) -> "s=" + s;        // Box<String> is inferred
        };
    }

    static String unpackAny(Box<?> b) {
        return switch (b) {
            case Box(var v) -> "v=" + v;
        };
    }

    public static void main(String[] args) {
        System.out.println(unpack(new Box<>("Java")));
        System.out.println(unpack(new Box<>(null)));
        System.out.println(unpackAny(new Box<>(null)));

        Object n = new Box<>(null);
        System.out.println(n instanceof Box<?>(String s));
        System.out.println(n instanceof Box<?>(Object s));
    }
}

Output:

s=Java
s=null
v=null
false
true
Pattern Component type Matches new Box<>(null)?
Box(String s) with a Box<String> selector String Yes, s = null: String s is unconditional for String
Box(var v) any Yes: var is always unconditional
Box<?>(Object s) ? (that is, Object) Yes: Object is unconditional for Object
Box<?>(String s) ? (that is, Object) No: the pattern narrows the type and performs an instanceof check, which null fails

The rule looks odd, but there's logic behind it: if a nested pattern checks nothing beyond what the component type already guarantees, it shouldn't reject null. Otherwise case Box(var v) wouldn't be exhaustive for Box<?>. If you don't want null in a component, check it in when or forbid it in the record's compact constructor.

Exhaustiveness for combinations

The compiler checks exhaustiveness for record patterns too, going through the combinations of sealed component types. In the example below no default is needed because every combination is covered:

// PairExhaustive.java
sealed interface Figure permits Round, Quad { }
record Round(double r) implements Figure { }
record Quad(double side) implements Figure { }
record Pair(Figure a, Figure b) { }

public class PairExhaustive {
    static String combine(Pair p) {
        return switch (p) {
            case Pair(Round a, Round b) -> "two circles";
            case Pair(Round a, Quad b)  -> "circle and square";
            case Pair(Quad a, Figure b) -> "square and anything";
        };
    }

    public static void main(String[] args) {
        System.out.println(combine(new Pair(new Round(1), new Quad(2))));
        System.out.println(combine(new Pair(new Quad(1), new Round(2))));
        try {
            System.out.println(combine(new Pair(null, new Round(1))));
        } catch (MatchException e) {
            System.out.println("MatchException");
        }
    }
}

Output:

circle and square
square and anything
MatchException

Remove the Pair(Round a, Quad b) branch and javac reports the switch expression does not cover all possible input values, because the “circle + square” pair is left unhandled. The last line of output shows the price of this check: the switch is exhaustive for all non-null components, and a pair with null inside matches no branch. Here the JVM throws not NullPointerException (the selector itself isn't null) but MatchException.

Unnamed patterns and the _ variable (Java 22)

Since Java 22 (JEP 456) you can replace an unneeded pattern variable with _: case Dog _ checks the type without declaring a variable; case Point(var x, _) skips the second component. The main practical consequence is several patterns in one label, separated by commas, which wasn't allowed before.

// UnnamedPatterns.java
sealed interface Animal permits Cat, Dog, Fish { }
record Cat(String name) implements Animal { }
record Dog(String name, int age) implements Animal { }
record Fish(String name) implements Animal { }

public class UnnamedPatterns {
    static String sound(Animal a) {
        return switch (a) {
            case Cat _, Fish _                 -> "doesn't bark";
            case Dog(_, int age) when age < 1  -> "puppy yaps";
            case Dog _                         -> "woof";
        };
    }

    public static void main(String[] args) {
        System.out.println(sound(new Cat("Whiskers")));
        System.out.println(sound(new Dog("Rex", 0)));
        System.out.println(sound(new Dog("Rex", 5)));
        System.out.println(sound(new Fish("Nemo")));
    }
}

Output:

doesn't bark
puppy yaps
woof
doesn't bark

Several patterns in one label are allowed only without named variables. case Integer i, String s -> gives error: illegal fall-through from a pattern: in the branch body there's no way to know which variable was initialized. Before Java 22 you had to write two branches with identical bodies.

The same _ works outside switch too — for unused variables in catch (Exception _), lambda parameters (k, _) -> k and loop variables. In Java 21 _ in patterns was available only as a preview.

Enums and qualified constants in switch

Since Java 21 a case label can use the fully qualified name of an enum constant — case Fiat.USD. You need it when the selector is a sealed interface implemented by several enums: the compiler couldn't tie a bare USD to a particular enum. Enum constants and type patterns can be mixed in one switch.

// EnumQualified.java
sealed interface Currency permits Fiat, Crypto { }
enum Fiat implements Currency { USD, EUR }
enum Crypto implements Currency { BTC, ETH }

public class EnumQualified {
    static String kind(Currency c) {
        return switch (c) {
            case Fiat.USD -> "dollar";
            case Fiat.EUR -> "euro";
            case Crypto cr -> "cryptocurrency " + cr.name().toLowerCase();
        };
    }

    public static void main(String[] args) {
        System.out.println(kind(Fiat.USD));
        System.out.println(kind(Fiat.EUR));
        System.out.println(kind(Crypto.BTC));
    }
}

Output:

dollar
euro
cryptocurrency btc

No default is needed: the compiler knows that a Currency is either a Fiat or a Crypto, every Fiat constant is listed, and Crypto is fully covered by the pattern. Dominance applies here too: put case Crypto cr above case Crypto.BTC and the constant becomes unreachable. A qualified name is also allowed in an ordinary switch over an enum — switch (fiat) { case Fiat.USD -> ... } — although the short USD is still the usual style there. How a sealed interface combines with enums and records is covered in Records and enums in a sealed hierarchy, and enums themselves in Enums in Java.

Pattern matching or polymorphism?

Pattern matching doesn't replace virtual methods; it solves the opposite problem. Polymorphism works best when new types are added often and the set of operations is stable. A switch over a sealed hierarchy works best when the set of types is fixed and new operations keep coming and shouldn't live inside the classes themselves.

Criterion Virtual method (polymorphism) switch over a sealed hierarchy
Where the logic lives In each class, next to the data In one method, separate from the data
Adding a new type One new class, no other code touched The compiler points to every switch that needs a new branch
Adding a new operation A new method in the interface and in every class One new method with a switch
Types from a third-party library You can't add a method to them Works if the hierarchy is sealed or there is a default
Typical use Plugins, strategies, hierarchies open for extension ASTs and interpreters, events, API responses, a success/error Result

This trade-off is known as the expression problem, and the style “records for data + a sealed interface + switch for behavior” is called data-oriented programming. The records are usually immutable — why that matters is explained in Immutable Classes in Java.

What's next: primitive types in patterns (preview)

The next step is primitive type patterns: case int i when i > 100, switch over boolean, long, float and double, and checks such as x instanceof byte b (“does the number fit into a byte without loss”). As of JDK 27 this is still a preview feature: it works only with the --enable-preview flag and may change.

JDK JEP Status
23 JEP 455 First preview
24 JEP 488 Second preview
25 JEP 507 Third preview
26 JEP 530 Fourth preview
27 (released September 15, 2026) JEP 532 Fifth preview

While the feature is in preview, the error primitive patterns are a preview feature and are disabled by default from Type patterns is expected behavior, not a compiler bug. Don't rely on it in production code: preview classes won't run without the same flag, and the syntax is still being refined between releases.

Common mistakes and javac messages

Almost every pattern matching mistake is caught by the compiler, and the message tells you exactly what to fix. The exceptions are null and side effects in when: they show up only at run time.

Mistake What javac or the JVM reports How to fix it
Subtype after supertype, unconditional pattern before when, pattern after default this case label is dominated by a preceding case label Specific to general: subtypes and when first, default last
Switch over Object without default the switch statement does not cover all possible input values (or switch expression) default, case Object o, or a sealed type with all variants
case Object o together with default switch has both an unconditional pattern and a default label Keep one of the two
Expecting case Object o or default to catch null NullPointerException at run time Add case null or case null, default
Pattern variable used in another branch or after the switch cannot find symbol Use the variable only in its own branch
case Integer i, String s -> illegal fall-through from a pattern Two branches, or case Integer _, String _ (Java 22+)
case 1 when x > 0 guards are only allowed for case with a pattern Check the condition in the branch body or switch to a pattern case Integer i when ...
Type pattern with an int selector primitive patterns are a preview feature and are disabled by default. An Integer/Object selector, or plain constants
Side effect in when (logging, a counter, modifying a collection) Compiles without warnings Move actions into the branch body

What interviews and the OCP exam ask

Pattern matching questions usually come as “does this snippet compile?”. The dominance and null rules from the sections above are asked most often, but less obvious variants come up too — they are collected in the table.

Code Result Why
case String s -> { s = s.trim(); return s; } Compiles A pattern variable is not implicitly final; you can forbid assignment explicitly: case final String s
switch (str) { case "a" -> 1; case String s -> 2; } with String str Compiles without default case String s is an unconditional pattern for String, so the switch is exhaustive
A switch statement with old-style labels: case String s: print(s); case Integer i: ... without break Doesn't compile Falling through into a label that declares a pattern variable is forbidden: illegal fall-through to a pattern
case Integer i when false -> ... Doesn't compile: this case label has a guard that is a constant expression with value 'false' A constant false guard makes the branch unreachable by definition
record R(int x); case R(long x) -> ... Doesn't compile without --enable-preview: primitive patterns are a preview feature and are disabled by default. Widening int → long in a pattern is part of the primitive patterns preview
case Integer i when i >= 0 and case Integer i when i < 0 with an Integer selector, no default Doesn't compile Guarded branches don't count toward exhaustiveness

Frequently asked questions

How is pattern matching for switch different from a regular switch on values?

A regular switch compares the selector with constants for equality and works only with primitives, their wrappers, String and enums. A switch with patterns checks the type and structure of an object, accepts a selector of any reference type, declares variables right in the label and must be exhaustive. You can mix both kinds of labels in one switch as long as the constants come before the patterns.

Which Java version introduced pattern matching for switch?

It has been standard since Java 21 (JEP 441 for switch, JEP 440 for record patterns). In Java 17–20 it was a preview feature behind --enable-preview, and in 17 and 18 the guard was written with && instead of when. Unnamed patterns _ are standard since Java 22; primitive type patterns are still in preview as of JDK 27.

Do I need default in a switch over a sealed interface?

No, and it's better to leave it out: without default the compiler points to every switch you have to update when a new subtype appears. For Object or a regular interface, default or an unconditional pattern is required. A worked example is in Exhaustiveness and in Sealed Classes and Interfaces in Java.

Why does a switch with case Object o throw NullPointerException?

A top-level pattern matches only objects, and null isn't an object; this keeps the old switch behavior. Only case null or case null, default catches null. An example with output is in null in switch.

Can I use when without a pattern, for example with a constant?

No. case 1 when x > 0 fails with guards are only allowed for case with a pattern. A guard can be attached only to a type pattern or a record pattern; for constants, put the check in the branch body.

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.