Pattern matching for switch

Before Java 21, a switch could only compare against constants. Pattern matching lets a case test the type of a value, bind it to a variable and add a condition, so a long chain of instanceof checks becomes one switch that the compiler checks for completeness. Every example was run on JDK 25, including a JMH speed test against an instanceof chain and a virtual method.

CsCode.ioUpdated
Share

Contents

Introduction

Until Java 21, a switch could only compare its value, the selector, with constants such as integers, strings and enum values. Code that had to act on the type of a value used a chain of if (o instanceof ...) else if .... Nothing checks such a chain for missing types, and it grows harder to read with every branch. Pattern matching for switch, final since Java 21, lets a case label be a pattern:

  • a type pattern, case Integer i, which matches any Integer and binds it to the variable i,
  • a record pattern, case Point(int x, int y), which also takes the record apart,
  • a guard, case Integer i when i < 0, which adds a condition,
  • case null, which handles a null selector inside the switch instead of throwing.

Two compiler rules make a pattern switch safer than an if chain. Under dominance, a case that can never match, because an earlier case already covers it, is a compile error. Under exhaustiveness, a switch that uses patterns must cover every possible value, either with default or, for sealed types and enums, by listing every case.

How the feature evolved
VersionChange
Java 17, 18First and second preview, with guards written as case Integer i && i < 0
Java 19, 20Third and fourth preview, where when replaced && for guards
Java 21Final, with qualified enum constants as labels and MatchException
Java 22Unnamed patterns _, allowing case Integer _, Long _
Java 23 to 27Preview: primitive types in patterns and as selectors

Every output below comes from JDK 25. All programs except the last need only Java 21. The last one uses a preview feature and needs --enable-preview.

Type patterns, guards and case null

This program shows the old if chain next to the new switch. It then runs the switch over values chosen to reach every case: a negative int for the guard, a number too large for an int, π, an empty and a non-empty string, an array, a list, a map, a LocalDate that only default handles, and null.

Java
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

public class TypeDispatch {

    // Before Java 21: an if-else chain of instanceof tests
    static String formatOld(Object o) {
        if (o == null) {
            return "null";
        } else if (o instanceof Integer i) {
            return "int " + i;
        } else if (o instanceof String s) {
            return "\"" + s + "\"";
        } else {
            return o.toString();
        }
    }

    // Java 21: the same dispatch as a switch with type patterns
    static String format(Object o) {
        return switch (o) {
            case null -> "null";
            case Integer i when i < 0 -> "negative int " + i;
            case Integer i -> "int " + i;
            case Long l -> "long " + l + "L";
            case Double d -> String.format("double %.2f", d);
            case String s when s.isEmpty() -> "empty string";
            case String s -> "\"" + s + "\"";
            case int[] arr -> "int array of length " + arr.length;
            case List<?> list -> "list of " + list.size();
            case Map<?, ?> map -> "map with keys " + map.keySet();
            default -> o.getClass().getSimpleName() + " " + o;
        };
    }

    public static void main(String[] args) {
        System.out.println(formatOld(42) + " | " + format(42));
        Object[] values = {-5, 9000000000L, Math.PI, "", "hi", new int[3], List.of(1, 2),
            Map.of("k", 1), LocalDate.of(2026, 1, 15), null};
        for (Object v : values) {
            System.out.println(format(v));
        }
    }
}

Running it prints:

Output
int 42 | int 42
negative int -5
long 9000000000L
double 3.14
empty string
"hi"
int array of length 3
list of 2
map with keys [k]
LocalDate 2026-01-15
null

Cases are tried from top to bottom, and the first match wins. The value -5 matched the guarded Integer case, while 42 failed the guard and matched the plain one. The number 9,000,000,000 does not fit in an int, so the literal is a long and matched case Long l. Patterns also work for arrays (int[] arr) and for generic types with wildcards (List<?> list).

Look at the last two lines. The LocalDate reached default, which a switch over Object needs in order to cover every value. The null went to case null. Without that label the switch would throw NullPointerException, as switches always have, because default alone does not catch null.

How a pattern switch runs

How does the JVM find the right case? javac does not turn the switch into a chain of instanceof tests. Running javap -c on TypeDispatch shows the start of format (shortened):

Output
static java.lang.String format(java.lang.Object);
  Code:
     0: aload_0
     1: astore_1
     2: iconst_0
     3: istore_2
     4: aload_1
     5: iload_2
     6: invokedynamic #24,  0   // InvokeDynamic #2:typeSwitch:(Ljava/lang/Object;I)I
    11: tableswitch   { // -1 to 8
                 -1: 64
                  0: 69
                  1: 95
                ...
            default: 252
        }
    64: ldc           #7        // String null
    ...
    69: aload_1
    70: checkcast     #9        // class java/lang/Integer
    73: astore_3
    74: aload_3
    75: invokevirtual #28       // Method java/lang/Integer.intValue:()I
    78: iflt          86
    81: iconst_1
    82: istore_2
    83: goto          4

Instruction 6 is a single invokedynamic call to SwitchBootstraps.typeSwitch, a method in the JDK. It receives the value and a restart index, tries the case types in order starting from that index, and returns the position of the first case that matches, or -1 for null. The tableswitch at instruction 11 then jumps to the code for that case. The picture shows the whole loop:

switch (o) calls typeSwitch with restart 0; typeSwitch returns the index of the first matching case; tableswitch jumps there; if the guard is false, a dashed arrow goes back to typeSwitch with restart set to that index plus 1.

The dashed arrow is the guard. Case 0 is case Integer i when i < 0. At instruction 78 the code checks i < 0. If it fails, instructions 81 to 83 set the restart index to 1 and jump back to the typeSwitch call, so the search continues with the next case, the plain case Integer i. That is how 42 reached the second case. Because the matching code lives in the JDK, it can get faster in a new JDK without recompiling your code.

Enum constants in a switch over a sealed interface

Enums can implement sealed interfaces, and since Java 21 a switch on the interface can use qualified enum constants such as case Suit.HEARTS next to type and record patterns. The example uses a sealed interface Card:

Java
// A card is one of three kinds, and no other class may implement Card
public sealed interface Card permits Suit, Joker, Custom {
}

Its three implementations are two enums and a record, each in its own file:

Java
public enum Suit implements Card { HEARTS, DIAMONDS, CLUBS, SPADES }
Java
public enum Joker implements Card { RED, BLACK }
Java
public record Custom(String text) implements Card {
}

The switch in describe lists the four suits by name, covers both jokers with one type pattern and takes the Custom record apart, so it needs no default:

Java
public class EnumAndSealed {
    static String describe(Card c) {
        return switch (c) {
            case Suit.HEARTS, Suit.DIAMONDS -> "red suit " + c;     // qualified enum constants
            case Suit.CLUBS, Suit.SPADES -> "black suit " + c;
            case Joker j -> j.name().toLowerCase() + " joker";       // a type pattern
            case Custom(String text) -> "custom card: " + text;      // a record pattern
        };
    }

    public static void main(String[] args) {
        Card[] cards = {Suit.HEARTS, Suit.SPADES, Joker.RED, new Custom("wild")};
        for (Card c : cards) {
            System.out.println(describe(c));
        }
    }
}

Running it prints:

Output
red suit HEARTS
black suit SPADES
red joker
custom card: wild

The compiler counts the four constants as covering Suit, and Joker j covers both jokers at once. Before Java 21, only the unqualified name (case HEARTS) was allowed, and only when the selector's type was the enum itself.

Exhaustiveness with generic sealed types

The compiler also uses type arguments when it decides which cases are possible. Here Holder<T> is a sealed generic interface:

Java
// A sealed generic interface with two implementations
public sealed interface Holder<T> permits TextHolder, ValueHolder {
}

A TextHolder is always a Holder<String>:

Java
// Always a Holder<String>, never a Holder of anything else
public record TextHolder(String text) implements Holder<String> {
}

A ValueHolder can hold any type:

Java
// A Holder<T> for any T
public record ValueHolder<T>(T value) implements Holder<T> {
}

The program has two switches, one over a Holder<Integer> and one over a Holder<?>:

Java
public class GenericExhaustive {
    // For a Holder<Integer>, a TextHolder is impossible, so one case covers everything
    static int unwrap(Holder<Integer> h) {
        return switch (h) {
            case ValueHolder<Integer>(Integer v) -> v;
        };
    }

    // For a Holder<?>, both kinds are possible, so both cases are needed
    static String show(Holder<?> h) {
        return switch (h) {
            case TextHolder(String text) -> "TextHolder with " + text;
            case ValueHolder<?>(var v) -> "ValueHolder with " + v;
        };
    }

    public static void main(String[] args) {
        int v = unwrap(new ValueHolder<>(41));
        System.out.println("unwrap: " + v + " + 1 = " + (v + 1));
        System.out.println(show(new TextHolder("hi")));
        System.out.println(show(new ValueHolder<>(3.5)));
    }
}

Running it prints:

Output
unwrap: 41 + 1 = 42
TextHolder with hi
ValueHolder with 3.5

The method unwrap has a single case and still compiles without default, because a Holder<Integer> can never be a TextHolder. Adding case TextHolder t to it is even a compile error: "incompatible types: Holder<Integer> cannot be converted to TextHolder". The method show takes a Holder<?>, where both kinds are possible, so it needs both cases.

What the compiler rejects

Which mistakes does the compiler catch? Each row below is one switch, compiled with javac 25 inside this method, with the cases from the middle column in place of the comment:

Java
int m(Object o) {
    return switch (o) {
        // the cases from the table go here
    };
}
Switches over an Object and what javac 25 says about them
What the switch doesCasesjavac says
A pattern switch on Object with no defaultcase String s -> 1; case Integer i -> 2;the switch expression does not cover all possible input values
A plain case before a guarded one of the same typecase Integer i -> 1; case Integer i when i > 0 -> 2; default -> 3;this case label is dominated by a preceding case label
An int constant when the selector is an Objectcase Integer i -> 1; case 42 -> 2; default -> 3;constant label of type int is not compatible with switch selector type Object
A guard that is always falsecase Integer i when false -> 1; default -> 2;this case label has a guard that is a constant expression with value 'false'
Falling through, with a colon, into a patterncase Integer i: System.out.println(i); case String s: yield 2; default: yield 3;illegal fall-through to a pattern
Two patterns that declare variables in one casecase Integer i, Long l -> 1; default -> 0;illegal fall-through from a pattern
The same with unnamed patterns (Java 22)case Integer _, Long _ -> 1; default -> 0;compiles
null together with a type patterncase null, String s -> 1; default -> 0;invalid case label combination
null together with defaultcase String s -> 1; case null, default -> 0;compiles

The first four rows are the safety rules at work. Without default, a switch over Object cannot cover every value. An unguarded case Integer i before the guarded one catches every Integer, so the guarded case could never run. A constant such as 42 needs a selector of a matching type, so switch on an Integer or use a guard instead. A guard that is the constant false can never match either.

The next three rows are about bindings. Falling into a pattern case would leave its variable without a value, and two patterns in one case cannot both bind their variables. With unnamed patterns (_), nothing is bound, so case Integer _, Long _ compiles. Last, null can share a case only with default, never with a type pattern.

Old switches keep their behaviour

Existing code is not affected. A switch that uses only constant labels still falls through with colons, still does not need to cover every value as a statement, and still throws on null. The example uses a small enum:

Java
public enum Level { LOW, MEDIUM, HIGH }

The program passes the same null to an old-style switch and to one with case null:

Java
public class OldSwitchRules {
    // A classic switch with constant labels behaves as it always did
    static int legacy(Level level) {
        switch (level) {
            case LOW:
                return 1;
            case MEDIUM:
                return 5;
            default:
                return 10;
        }
    }

    // Adding case null turns a null selector from an exception into a branch
    static int withNull(Level level) {
        return switch (level) {
            case null -> 0;
            case LOW -> 1;
            case MEDIUM -> 5;
            case HIGH -> 10;
        };
    }

    public static void main(String[] args) {
        System.out.println("legacy(HIGH)   = " + legacy(Level.HIGH));
        System.out.println("withNull(null) = " + withNull(null));
        try {
            legacy(null);
        } catch (NullPointerException e) {
            System.out.println("legacy(null)   -> NullPointerException");
        }
    }
}

Running it prints:

Output
legacy(HIGH)   = 10
withNull(null) = 0
legacy(null)   -> NullPointerException

The call legacy(HIGH) reached default and returned 10. With null, legacy threw NullPointerException before any case was considered, while withNull returned 0. Adding case null to an enum switch also makes it a pattern switch, so it must be exhaustive, which is why withNull lists all three levels.

How fast is a pattern switch?

A pattern switch replaces two older designs, an instanceof chain and a method on the interface that each class overrides. Is it slower than either? The test computes the area of shapes in all three ways. Every shape implements a sealed interface:

Java
package shapes;

public sealed interface Shape permits Circle, Square, Rect, Tri {
    double area();
}

The four shapes are records, each with its own area():

Java
package shapes;

public record Circle(double r) implements Shape {
    public double area() {
        return 3.0 * r * r;
    }
}
Java
package shapes;

public record Square(double s) implements Shape {
    public double area() {
        return s * s;
    }
}
Java
package shapes;

public record Rect(double w, double h) implements Shape {
    public double area() {
        return w * h;
    }
}
Java
package shapes;

public record Tri(double b, double h) implements Shape {
    public double area() {
        return 0.5 * b * h;
    }
}

The same calculation as a pattern switch and as an instanceof chain:

Java
package shapes;

// The same area calculation written as a pattern switch and as an instanceof chain
public class Areas {
    static double bySwitch(Shape s) {
        return switch (s) {
            case Circle c -> 3.0 * c.r() * c.r();
            case Square q -> q.s() * q.s();
            case Rect r -> r.w() * r.h();
            case Tri t -> 0.5 * t.b() * t.h();
        };
    }

    static double byIfChain(Shape s) {
        if (s instanceof Circle c) {
            return 3.0 * c.r() * c.r();
        } else if (s instanceof Square q) {
            return q.s() * q.s();
        } else if (s instanceof Rect r) {
            return r.w() * r.h();
        } else if (s instanceof Tri t) {
            return 0.5 * t.b() * t.h();
        }
        throw new IllegalArgumentException("unknown shape " + s);
    }
}

The benchmark uses JMH. It fills an array with 10,000 shapes of all four types, mixed at random with a fixed seed, and each benchmark adds up their areas in one of the three ways:

Java
package shapes;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class AreaBench {
    Shape[] shapes = new Shape[10000];

    @Setup
    public void fill() {
        Random random = new Random(42);                // all four types, mixed at random
        for (int i = 0; i < shapes.length; i++) {
            shapes[i] = switch (random.nextInt(4)) {
                case 0 -> new Circle(1);
                case 1 -> new Square(2);
                case 2 -> new Rect(1, 3);
                default -> new Tri(2, 2);
            };
        }
    }

    @Benchmark
    public double patternSwitch() {
        double sum = 0;
        for (Shape s : shapes) {
            sum += Areas.bySwitch(s);
        }
        return sum;
    }

    @Benchmark
    public double instanceofChain() {
        double sum = 0;
        for (Shape s : shapes) {
            sum += Areas.byIfChain(s);
        }
        return sum;
    }

    @Benchmark
    public double virtualMethod() {
        double sum = 0;
        for (Shape s : shapes) {
            sum += s.area();
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {
        new Runner(new OptionsBuilder()
                .include(AreaBench.class.getName())
                .forks(3)                                       // 3 fresh JVMs per benchmark
                .warmupIterations(5).warmupTime(TimeValue.seconds(1))
                .measurementIterations(5).measurementTime(TimeValue.seconds(1))
                .build()).run();
    }
}

The results, on a 2-CPU Linux machine with JDK 25 (times for one pass over the 10,000 shapes):

Output
Benchmark                  Mode  Cnt    Score   Error  Units
AreaBench.instanceofChain  avgt   15   66.509 ± 3.429  us/op
AreaBench.patternSwitch    avgt   15   67.818 ± 7.351  us/op
AreaBench.virtualMethod    avgt   15  170.541 ± 5.788  us/op

The pattern switch and the instanceof chain took the same time, about 67 µs, with error ranges that overlap. The virtual method took 170 µs, about 2.5 times as long. Running the benchmarks again with -XX:+PrintInlining shows why. For s.area(), the JIT reported "failed to inline: virtual call", because four different classes reach that one call. For the pattern switch, the JDK generated a small class for the typeSwitch call (Areas$$TypeSwitch), and the JIT inlined it.

So a pattern switch over a sealed type costs no more than an instanceof chain, and here it beat the virtual call. That does not make virtual methods wrong. Choose between them by design. Use a method on the interface when new types keep arriving, and a switch when the set of types is closed and new operations keep arriving.

Primitive selectors and patterns (preview)

A preview feature first shown in Java 23 lets switch work on long, float, double and boolean selectors and allows primitive type patterns with guards. It is still in preview in Java 27, and JEP 532 has the latest details. The inputs below include HTTP codes on both sides of the 400 and 500 boundaries, both zeros and NaN, and a long above the int range:

Java
public class PrimitiveSwitch {

    // Java 25 preview: guards on a primitive selector, no boxing
    static String httpStatus(int code) {
        return switch (code) {
            case 200 -> "OK";
            case 404 -> "Not Found";
            case int c when c >= 500 -> "server error " + c;
            case int c when c >= 400 -> "client error " + c;
            case int c -> "other " + c;
        };
    }

    // Selectors of type long, double and boolean were not allowed before
    static String sign(double d) {
        return switch (d) {
            case 0.0 -> "zero";
            case double x when x > 0 -> "positive";
            case double x when x < 0 -> "negative";
            case double x -> "not a number";
        };
    }

    static String flag(boolean b) {
        return switch (b) {
            case true -> "on";
            case false -> "off";
        };
    }

    public static void main(String[] args) {
        for (int code : new int[] {200, 404, 418, 503, 302}) {
            System.out.println(code + " -> " + httpStatus(code));
        }
        for (double d : new double[] {0.0, -0.0, 2.5, -1, Double.NaN}) {
            System.out.println(d + " -> " + sign(d));
        }
        System.out.println("true -> " + flag(true) + ", false -> " + flag(false));
        long big = 3000000000L;
        System.out.println(big + " -> " + switch (big) {
            case long l when l > Integer.MAX_VALUE -> "too big for an int";
            case long l -> "fits in an int";
        });
    }
}

Compiled with --enable-preview --release 25 and run with --enable-preview on JDK 25, it prints:

Output
200 -> OK
404 -> Not Found
418 -> client error 418
503 -> server error 503
302 -> other 302
0.0 -> zero
-0.0 -> not a number
2.5 -> positive
-1.0 -> negative
NaN -> not a number
true -> on, false -> off
3000000000 -> too big for an int

The codes 418 and 503 reached the guarded cases, and 302 reached the final case int c, which works like default and makes the switch exhaustive. A boolean switch with true and false is exhaustive too, and the long 3,000,000,000 was handled without narrowing it to an int.

Now look at -0.0, which printed "not a number". The constant label case 0.0 compares like Double.equals, which treats 0.0 and -0.0 as different, and -0.0 is neither greater nor less than 0. So the last case, written for NaN, also caught negative zero. Preview features can still change before they become final, so keep them out of production code.

Which construct to use

Choosing between switch forms and alternatives
SituationUse
Compare against constants (numbers, strings, enum values)A switch expression with arrow labels
Act on the runtime type of a valuePattern switch with type patterns
A closed set of typesSealed interface and an exhaustive switch without default
Need the components of a recordRecord patterns as case labels
A value may be nullcase null, or case null, default
One type test with a conditioninstanceof with a pattern
Behaviour that belongs to an open set of typesA virtual method on the interface

Sealed hierarchies themselves, and how records and patterns work with them, are covered in sealed types with pattern matching.