Sub topic 14
Pattern Matching for Switch and Record Patterns
In the last chapter you built sealed interfaces from records and enums. Now you will learn the payoff. Java 21 lets a switch check what kind of object it has and pull the data out of it in the same step. This chapter shows you how.
What Is Pattern Matching?
A pattern is a small test that Java runs on a value. If the test passes, Java can also give names to parts of that value. Pattern matching means checking a value against patterns and acting on the first one that fits.
You have already used one kind of pattern without noticing. A type pattern checks the type of a value and gives it a name:
Object obj = "hello";
if (obj instanceof String s) {
System.out.println(s.length()); // 5
}The part String s is the type pattern. If obj is a String, Java creates the variable s with the right type. You do not need a cast.
Why It Matters
Before Java 21, code that handled different shapes looked like this:
if (shape instanceof Circle) {
Circle c = (Circle) shape;
// use c.radius()
} else if (shape instanceof Square) {
Square s = (Square) shape;
// use s.side()
}This code has three problems:
- It repeats each type name twice.
- A cast can fail if you make a typing mistake.
- If someone adds a new shape, the compiler stays quiet and the new shape is silently skipped.
Pattern matching for switch fixes all three.
Type Patterns in a Switch
A switch can now use type patterns as its case labels. Here is a full program you can save as Main.java and run with java Main.java:
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
public class Main {
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Rectangle r -> r.width() * r.height();
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(1))); // 3.141592653589793
System.out.println(area(new Square(3))); // 9.0
System.out.println(area(new Rectangle(2, 5))); // 10.0
}
}Each case tests the type. When a test passes, the variable (c, s, or r) holds the shape with its exact type.
Notice there is no default branch. Shape is sealed, so the compiler knows the full list of shapes. The switch is exhaustive, which means it covers every possible case. If you add record Triangle(...) implements Shape and update the permits list, the compiler will report an error in area until you add a Triangle case. That error is a feature: the compiler finds every place you forgot to update.
Record Patterns: Unpacking in One Step
A record pattern goes one step further. It matches a record and pulls out its components into new variables. Pulling components out like this is called deconstruction.
Compare these two cases:
case Square s -> s.side() * s.side(); // type pattern
case Square(double side) -> side * side; // record patternThe record pattern Square(double side) reads as: "if this is a Square, call its side() accessor and put the result in side." You list the components in the same order as the record header.
Here is area rewritten with record patterns:
static double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
case Rectangle(double w, double h) -> w * h;
};
}The names in the pattern do not have to match the component names. Circle(double r) works even though the component is called radius. Only the order and types matter.
Using `var` in Record Patterns
You can write var instead of the type, and Java will work out the type for you:
case Rectangle(var w, var h) -> w * h;This is handy when component types are long, such as List<String>.
Record Patterns with `instanceof`
Record patterns also work outside a switch:
record Point(int x, int y) {}
Object obj = new Point(3, 4);
if (obj instanceof Point(int x, int y)) {
System.out.println(x + y); // 7
}How Java Picks a Case
Java checks the cases from top to bottom. The first case whose pattern matches wins. The diagram below shows the flow.
Guards: Adding Extra Conditions with `when`
Sometimes the type alone is not enough. A guard is an extra true-or-false test attached to a case with the word when. The case only runs if both the pattern matches and the guard is true.
static String describe(Shape shape) {
return switch (shape) {
case Circle(double r) when r == 0 -> "a dot";
case Circle(double r) -> "a circle of radius " + r;
case Square(double side) when side > 100 -> "a huge square";
case Square(double side) -> "a square";
case Rectangle(double w, double h) when w == h -> "a square-shaped rectangle";
case Rectangle r -> "a rectangle";
};
}Guarded cases do not count toward exhaustiveness. The compiler cannot know if r == 0 covers every circle, so you still need the plain case Circle(double r) line.
The Order Trap: Dominance
Order matters. Look at this broken version:
case Circle(double r) -> "a circle";
case Circle(double r) when r == 0 -> "a dot"; // compile errorThe first case matches every circle, so the second can never run. Java calls this dominance: the first case dominates the second. The compiler rejects it with an error like "this case label is dominated by a preceding case label." The fix is to put the more specific case first.
Nested Record Patterns
Records often hold other records. Record patterns can be nested inside each other to reach deep data in one line.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
public class Main {
static String classify(Line line) {
return switch (line) {
case Line(Point(var x1, var y1), Point(var x2, var y2)) when x1 == x2 && y1 == y2 ->
"a single point";
case Line(Point(var x1, var y1), Point(var x2, var y2)) when x1 == x2 ->
"vertical";
case Line(Point(var x1, var y1), Point(var x2, var y2)) when y1 == y2 ->
"horizontal";
case Line l -> "slanted";
};
}
public static void main(String[] args) {
System.out.println(classify(new Line(new Point(1, 1), new Point(1, 1)))); // a single point
System.out.println(classify(new Line(new Point(0, 0), new Point(0, 5)))); // vertical
System.out.println(classify(new Line(new Point(0, 2), new Point(7, 2)))); // horizontal
System.out.println(classify(new Line(new Point(0, 0), new Point(3, 4)))); // slanted
}
}Without nesting you would call line.start().x() and similar accessors many times. The pattern names all four numbers at once.
Handling `null`
By default, a switch throws a NullPointerException when the value is null. Java 21 lets you handle it on purpose with case null:
static String describeOrNone(Shape shape) {
return switch (shape) {
case null -> "no shape";
case Circle c -> "circle";
case Square s -> "square";
case Rectangle r -> "rectangle";
};
}You can also combine it with default as case null, default -> ... when you switch over a type that is not sealed, such as Object.
Mixing Records and Enums
A sealed interface can permit both records and enums. A pattern switch handles both. In this tiny calculator, a token is either a number or an operator:
sealed interface Token permits Num, Op {}
record Num(int value) implements Token {}
enum Op implements Token { PLUS, MINUS }
public class Main {
static String show(Token token) {
return switch (token) {
case Num(int v) when v < 0 -> "negative number " + v;
case Num(int v) -> "number " + v;
case Op op -> switch (op) {
case PLUS -> "plus sign";
case MINUS -> "minus sign";
};
};
}
public static void main(String[] args) {
System.out.println(show(new Num(42))); // number 42
System.out.println(show(new Num(-3))); // negative number -3
System.out.println(show(Op.MINUS)); // minus sign
}
}The outer switch uses patterns. The inner switch is an ordinary enum switch like the ones from earlier chapters. Both are exhaustive, so neither needs a default.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Plain case before a guarded case of the same type | Compile error: label is dominated | Put the guarded case first |
| Only guarded cases for a type | Compile error: switch not exhaustive | Add an unguarded case for that type |
| Wrong number of components in a record pattern | Compile error | Match the record header exactly |
| Forgetting `null` | `NullPointerException` at run time | Add `case null` if null is possible |
| Adding `default` to a sealed switch | Compiles, but hides missing cases later | Leave `default` out so the compiler can warn you |
The last row needs explaining. A default branch catches everything, so when someone adds a new record to the sealed interface, the compiler stays silent. Leaving default out keeps the compiler checking for you.
Summary
- A type pattern (
Circle c) tests a type and names the value. - A record pattern (
Circle(double r)) tests a type and unpacks its components. - Record patterns can be nested and can use
var. - A
whenguard adds an extra condition. Put guarded cases before plain ones. - With sealed interfaces, the compiler checks that every case is covered, so you need no
default. case nullhandles null on purpose instead of crashing.
Exercise
Write a method perimeter(Shape shape) for the sealed Shape interface with Circle(double radius), Square(double side), and Rectangle(double width, double height). Use record patterns and no default branch.
Show answer
static double perimeter(Shape shape) { return switch (shape) { case Circle(double r) -> 2 Math.PI r; case Square(double side) -> 4 side; case Rectangle(double w, double h) -> 2 (w + h); }; } Because Shape is sealed and all three records are covered, the switch is exhaustive and compiles without a default.
Exercise
This switch does not compile. Why, and how do you fix it? case Square s -> "square"; case Square s when s.side() == 0 -> "empty square";
Show answer
The first case matches every Square, so it dominates the second case and the guarded case can never run. Swap the order so the guarded case comes first: case Square s when s.side() == 0 -> "empty square"; then case Square s -> "square";
Exercise
Given record Point(int x, int y) and record Line(Point start, Point end), write one case label using a nested record pattern that matches only lines that start at the origin (0, 0).
Show answer
case Line(Point(var x, var y), Point end) when x == 0 && y == 0 -> "starts at origin"; The nested pattern unpacks the start point, and the guard checks both coordinates. You still need a plain case such as case Line l -> ... after it so the switch is exhaustive.