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.
Contents
Introduction Type patterns, guards and case null How a pattern switch runs Enum constants in a switch over a sealed interface Exhaustiveness with generic sealed types What the compiler rejects Old switches keep their behaviour How fast is a pattern switch? Primitive selectors and patterns (preview) Which construct to use
Introduction
Until Java 21, a switchif (o instanceof ...) else if ...
- a type pattern,
, which matches anycase Integer i and binds it to the variableInteger ,i - a record pattern,
, which also takes the record apart,case Point(int x, int y) - a guard,
, which adds a condition,case Integer i when i < 0 , which handles acase null selector inside the switch instead of throwing.null
Two compiler rules make a pattern switch safer than an ifdefault
| Version | Change |
|---|---|
| Java 17, 18 | First and second preview, with guards written as case Integer i && i < 0 |
| Java 19, 20 | Third and fourth preview, where when&& |
| Java 21 | Final, with qualified enum constants as labels and MatchException |
| Java 22 | Unnamed patterns _case Integer _, Long _ |
| Java 23 to 27 | Preview: 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 ifintintLocalDatedefaultnull
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:
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 Integerintlongcase Long lint[] arrList<?> list
Look at the last two lines. The LocalDatedefaultObjectnullcase nullNullPointerExceptiondefaultnull
How a pattern switch runs
How does the JVM find the right case? javac does not turn the switch into a chain of instanceofjavap -cTypeDispatchformat
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 invokedynamicSwitchBootstraps.typeSwitchnulltableswitch
The dashed arrow is the guard. Case 0 is case Integer i when i < 0i < 0typeSwitchcase Integer i
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.HEARTSCard
// 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:
public enum Suit implements Card { HEARTS, DIAMONDS, CLUBS, SPADES }
public enum Joker implements Card { RED, BLACK }
public record Custom(String text) implements Card {
}
The switch in describeCustomdefault
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:
red suit HEARTS
black suit SPADES
red joker
custom card: wild
The compiler counts the four constants as covering SuitJoker jcase HEARTS
Exhaustiveness with generic sealed types
The compiler also uses type arguments when it decides which cases are possible. Here Holder<T>
// A sealed generic interface with two implementations
public sealed interface Holder<T> permits TextHolder, ValueHolder {
}
A TextHolderHolder<String>
// Always a Holder<String>, never a Holder of anything else
public record TextHolder(String text) implements Holder<String> {
}
A ValueHolder
// 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>Holder<?>
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:
unwrap: 41 + 1 = 42
TextHolder with hi
ValueHolder with 3.5
The method unwrapdefaultHolder<Integer>TextHoldercase TextHolder tshowHolder<?>
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:
int m(Object o) {
return switch (o) {
// the cases from the table go here
};
}
| What the switch does | Cases | javac says |
|---|---|---|
A pattern switch on Objectdefault | case 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 type | case Integer i -> 1; case Integer i when i > 0 -> 2; default -> 3; | this case label is dominated by a preceding case label |
An intObject | case 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 false | case 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 pattern | case 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 case | case 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 | case null, String s -> 1; default -> 0; | invalid case label combination |
nulldefault | case String s -> 1; case null, default -> 0; | compiles |
The first four rows are the safety rules at work. Without defaultObjectcase Integer iInteger42Integerfalse
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 (_case Integer _, Long _nulldefault
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
public enum Level { LOW, MEDIUM, HIGH }
The program passes the same nullcase null
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:
legacy(HIGH) = 10
withNull(null) = 0
legacy(null) -> NullPointerException
The call legacy(HIGH)defaultnulllegacyNullPointerExceptionwithNullcase nullwithNull
How fast is a pattern switch?
A pattern switch replaces two older designs, an instanceof
package shapes;
public sealed interface Shape permits Circle, Square, Rect, Tri {
double area();
}
The four shapes are records, each with its own area()
package shapes;
public record Circle(double r) implements Shape {
public double area() {
return 3.0 * r * r;
}
}
package shapes;
public record Square(double s) implements Shape {
public double area() {
return s * s;
}
}
package shapes;
public record Rect(double w, double h) implements Shape {
public double area() {
return w * h;
}
}
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
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
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):
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-XX:+PrintInlinings.area()typeSwitchAreas$$TypeSwitch
So a pattern switch over a sealed type costs no more than an instanceof
Primitive selectors and patterns (preview)
A preview feature first shown in Java 23 lets switchlongfloatdoublebooleanlongint
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--enable-preview
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 cdefaultbooleantruefalselongint
Now look at -0.0, which printed "not a number". The constant label case 0.0Double.equals
Which construct to use
| Situation | Use |
|---|---|
| Compare against constants (numbers, strings, enum values) | A |
| Act on the runtime type of a value | Pattern switch with type patterns |
| A closed set of types | Sealed interface and an exhaustive switch without default |
| Need the components of a record | Record patterns as case labels |
A value may be null | case nullcase null, default |
| One type test with a condition | |
| Behaviour that belongs to an open set of types | A virtual method on the interface |
Sealed hierarchies themselves, and how records and patterns work with them, are covered in