Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
The Java 21 pattern switch for the OCP exam: type patterns on any reference type, when guards, dominance and branch order, exhaustive statements, case null and case null, default, record patterns, and sealed types without a default.
kvi5hnuCode Sprout team member11 min readOn this page
Article 12 used switch with constant case values. Java 21 finalized pattern matching for switch (JEP 441) and record patterns (JEP 440), so a case can now test the type of the selector, bind a variable, add a condition, match null and take a record apart. This is one of the most heavily tested topics on the 1Z0-830 exam, and most questions come down to a few rules: which types are allowed, which order the branches must be in, and when the switch is exhaustive.
Type patterns in case
A pattern switch works on any reference type. Each case names a type and a pattern variable, just like instanceof (article 11):
String describe(Number height) {
return switch (height) {
case Integer i -> "whole number " + i;
case Double d -> "decimal " + d;
case Number n -> "some other number " + n;
};
}
The rules carry over from instanceof:
- A pattern variable is in scope only in its own branch (and its guard), so two branches can both use
i. - A pattern variable is not implicitly
final, so you can reassign it inside its branch. You rarely should. - The pattern type must be the selector type or a type that could be cast from it. A
case String sin a switch onNumberfails with "incompatible types: Number cannot be converted to String".
Pattern switches work as statements or expressions, with arrow labels or colon labels. The arrow form is far more common.
Constant labels and type patterns can share a switch, as long as the constants fit the selector type. On an Integer selector, case 1 -> and case Integer i -> can sit side by side. On an Object selector, case "a" is an error ("constant label of type String is not compatible with switch selector type Object"). Use case String s when s.equals("a") instead.
Guards with when
A guard adds a boolean condition after the pattern, introduced by the contextual keyword when:
String trainerFor(Number height) {
return switch (height) {
case Integer i when i > 10 -> "large-animal team";
case Integer i -> "small-animal team";
case Double d when d <= 15.5 -> "precision team A";
case Double d -> "precision team B";
case Number n -> "generalists";
};
}
A branch matches only if the type matches and the guard is true. Guards are what finally let switch test ranges, which constant labels never could.
Guard rules:
- The guard can use the pattern variable and any
&&,||or method call that yields aboolean. - Local variables from outside the switch used in a guard must be
finalor effectively final ("local variables referenced from a guard must be final or effectively final"). - A guard that is the constant
falseis an error ("this case label has a guard that is a constant expression with value 'false'"). The constanttruecompiles. instanceofused&&for its condition. Inside acase, the keyword must bewhen;case Integer i && i > 10doesn't compile.
Order matters: dominance
In a constant-only switch expression, branch order doesn't matter. In a pattern switch it always matters, because the branches are tried from top to bottom and the first match wins. The compiler rejects a label that can never be reached because an earlier one catches everything it would. The error is "this case label is dominated by a preceding case label".

| Order | Compiles? | Why |
|---|---|---|
case Integer i then case Number n | Yes | Specific type first |
case Number n then case Integer i | No | Number dominates Integer |
case CharSequence cs then case String s | No | String is a CharSequence |
case Integer i when i > 10 then case Integer i | Yes | Guarded first |
case Integer i then case Integer i when i > 10 | No | The unguarded label catches everything |
case "a" then case String s | Yes | Constant first |
case String s then case "a" | No | The pattern catches "a" |
default then case Integer i | No | default dominates patterns |
A guarded label never dominates anything, because the compiler can't know when the guard is true. Two guarded labels of the same type can be in any order, but only the first matching one runs.
Exhaustive pattern switches
Article 12 said that switch expressions must be exhaustive. With patterns, switch statements must be exhaustive too. These both fail with "does not cover all possible input values":
Number visitors = 1_000;
switch (visitors) { // DOES NOT COMPILE
case Integer count -> System.out.println(count);
}
There are three fixes:
- Make the last pattern unconditional, meaning its type is the selector type or a supertype: add
case Number n -> …. (An unguarded pattern of the selector type is called the total or unconditional pattern.) - Add
default -> …. - Change the selector type so the patterns cover it, for example declare
visitorsasInteger.
Using both 1 and 2 fails, in any order. The compiler reports "switch has both an unconditional pattern and a default label" for either order. (A default placed before a pattern label that isn't unconditional is reported as "dominated".) A guarded label never counts toward exhaustiveness.
Sealed types and enums
A sealed interface or class (Chapter 7) lists all its permitted subtypes, so the compiler can check coverage without a default:
sealed interface Shape permits Circle, Rect, Square {}
record Circle(double radius) implements Shape {}
record Rect(double width, double height) implements Shape {}
record Square(double side) implements Shape {}
double area(Shape s) {
return switch (s) { // exhaustive: all three permitted types covered
case Circle c -> Math.PI * c.radius() * c.radius();
case Rect r -> r.width() * r.height();
case Square q -> q.side() * q.side();
};
}
Leave out Square and it's a compile error. That is the point: when someone adds a fourth shape, every switch that needs updating fails to compile. Enum constants work the same way, and since Java 21 a sealed interface implemented by an enum can be covered with qualified constants such as case Suit.HEARTS.
Handling null
Every switch, including a pattern switch, throws a NullPointerException when the selector is null, unless it has a case null label. Neither default nor case Object o matches null.
String greet(String pass) {
return switch (pass) {
case "VIP" -> "Welcome back!";
case null -> "No pass?";
default -> "Hello";
};
}
Rules for case null, all checked by the compiler:
case nullworks with any reference-type selector, includingString, enums and wrappers.- A switch that contains
case nullcounts as a pattern switch. A statement withcase nulltherefore has to be exhaustive.switch (s) { case "a": break; case null: break; }fails without adefault. case nullcan appear anywhere beforedefault. Afterdefaultit's dominated.case null, default ->combines both into one branch. That's the only label combination allowed withnull.case null, String sis an "invalid case label combination".
Record patterns
A record pattern matches a record and binds its components in one step (records themselves are covered in Chapter 7):
record Point(int x, int y) {}
String where(Object o) {
return switch (o) {
case Point(int x, int y) when x == y -> "on the diagonal";
case Point(var x, var y) -> "at " + x + "," + y;
default -> "not a point";
};
}
- The nested patterns follow the record's component order, and there must be exactly one per component ("incorrect number of nested patterns").
- Each component pattern is a type pattern,
var, or another record pattern. Nesting is allowed:case Line(Point(var x1, var y1), Point p2). - Component types must match. For an
intcomponent,int xandvar xwork.long xis a primitive pattern, which needs the preview feature. For anIntegercomponent,int xdoesn't compile in Java 21. - Type arguments are inferred: with
record Box<T>(T t),case Box(var s)on aBox<String>givessthe typeString. - Record patterns work with
instanceoftoo:if (o instanceof Point(int x, int y) && x > 0). - Java 21 has no name for the whole record in a record pattern.
case Point(int x, int y) pwas in the preview and was removed before it became final.
null inside a record: a record pattern never matches a null record. For components, a var or total-type component pattern does match null, but a narrower type pattern doesn't. With record Box(Object content), new Box(null) doesn't match Box(String s) but does match Box(var v).
A record pattern over a sealed hierarchy can make a switch exhaustive with no default, as long as every combination of components is covered.
Fall-through and patterns
Colon labels still work with patterns, but you can't fall into a pattern, because its variable would never have been bound. case Integer i: … without break, followed by case String s:, fails with "illegal fall-through to a pattern". One label also can't carry two patterns that declare variables: case Integer i, String s -> fails with "illegal fall-through from a pattern".
What's current
- Pattern matching for
switchand record patterns became final in Java 21 and are the heart of 1Z0-830. - Java 22 added unnamed patterns (
case Integer _, Long _). Primitive patterns are still a preview through Java 25.
Exam traps from this article
A complete example
import java.util.List;
public class Solution {
sealed interface Shape permits Circle, Rect, Square {}
record Circle(double radius) implements Shape {}
record Rect(double width, double height) implements Shape {}
record Square(double side) implements Shape {}
record Point(int x, int y) {}
record Line(Point from, Point to) {}
record Box(Object content) {}
// Type patterns, guards, case null and default in one switch
static String describe(Object o) {
return switch (o) {
case null -> "nothing";
case Integer i when i < 0 -> "negative int " + i;
case Integer i -> "int " + i;
case Long l -> "long " + l;
case String s when s.isBlank() -> "blank text";
case String s -> "text of length " + s.length();
case int[] arr -> "int array of " + arr.length;
default -> "other " + o.getClass().getSimpleName();
};
}
// Sealed interface: no default needed, the three records cover it
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rect(double w, double h) -> w * h;
case Square(var side) -> side * side;
};
}
// Nested record patterns pull out four ints at once
static String lineKind(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(Point from, Point to) -> "slanted from " + from + " to " + to;
};
}
// A var component matches null, a type component does not
static String unbox(Box box) {
return switch (box) {
case Box(String s) -> "box of text " + s;
case Box(var other) -> "box holding " + other;
};
}
// A pattern switch statement must be exhaustive too
static void inspect(Shape shape) {
switch (shape) {
case Circle c -> System.out.println(" circle, r=" + c.radius());
case Rect r -> System.out.println(" rectangle " + r.width() + "x" + r.height());
case Square s -> System.out.println(" square " + s.side());
}
}
public static void main(String[] args) {
System.out.println("-- type patterns and guards --");
List<Object> values = List.of(-4, 12, 7L, " ", "parrot", new int[3], 2.5);
for (Object v : values) {
System.out.println(describe(v));
}
System.out.println(describe(null));
System.out.println("-- record patterns over a sealed type --");
List<Shape> shapes = List.of(new Circle(1), new Rect(2, 3), new Square(4));
for (Shape s : shapes) {
System.out.printf("%s -> %.2f%n", s, area(s));
inspect(s);
}
System.out.println("-- nested record patterns --");
System.out.println(lineKind(new Line(new Point(1, 1), new Point(1, 1))));
System.out.println(lineKind(new Line(new Point(2, 0), new Point(2, 9))));
System.out.println(lineKind(new Line(new Point(0, 5), new Point(8, 5))));
System.out.println(lineKind(new Line(new Point(0, 0), new Point(3, 4))));
System.out.println("-- null inside and outside a record --");
System.out.println(unbox(new Box("map")));
System.out.println(unbox(new Box(42)));
System.out.println(unbox(new Box(null)));
try {
System.out.println(unbox(null));
} catch (NullPointerException e) {
System.out.println("null selector without case null: NullPointerException");
}
}
}
Output:
-- type patterns and guards --
negative int -4
int 12
long 7
blank text
text of length 6
int array of 3
other Double
nothing
-- record patterns over a sealed type --
Circle[radius=1.0] -> 3.14
circle, r=1.0
Rect[width=2.0, height=3.0] -> 6.00
rectangle 2.0x3.0
Square[side=4.0] -> 16.00
square 4.0
-- nested record patterns --
a single point
vertical
horizontal
slanted from Point[x=0, y=0] to Point[x=3, y=4]
-- null inside and outside a record --
box of text map
box holding 42
box holding null
null selector without case null: NullPointerException
Points to notice:
describehas a guardedIntegerlabel before the unguarded one and a guardedStringlabel before the plain one. Reversing either pair would not compile.int[]is a reference type, so an array type pattern is allowed.areaandinspecthave nodefault. The sealed interface makes them exhaustive, andinspectis a statement that the compiler still checks.lineKinduses nested record patterns with guards. The last, unguarded label makes it exhaustive.unbox(new Box(null))matches thevarcomponent, notString s.unbox(null)throws, because the switch has nocase null.
Common questions
What does pattern matching for switch replace?
Chains of if (o instanceof A a) … else if (o instanceof B b) …. The switch is shorter, the compiler checks the order, and with sealed types it checks that every case is handled.
Does case Object o match null?
No. Only case null matches a null selector. Without it, the switch throws a NullPointerException before trying any label. Inside a record pattern, a var or total-type component does match a null component.
When do I need a default?
When the patterns don't already cover every possible value of the selector type. You don't need one when the last pattern is unconditional or when every subtype of a sealed type, or every enum constant, is covered. You can't have both a default and an unconditional pattern.
Is when a reserved keyword?
No. It's a contextual keyword that only has meaning after a pattern in a case label, so int when = 3; still compiles. The same goes for yield, record, sealed and permits.
Can a guard have side effects? It can call any method. Guards run in label order, and only until one label matches, so a side effect may or may not happen depending on the value. Keep guards free of side effects.
Summary
- A
casecan hold a type pattern on any reference selector. Its variable is scoped to that branch. whenadds a guard. Guard locals must be effectively final, and a constantfalseguard is an error.- Pattern branches are tried top to bottom. Specific before general, guarded before unguarded, constants before their type,
defaultlast. Otherwise the label is "dominated". - Pattern switch statements and expressions must be exhaustive: use an unconditional pattern, a
default(never both), or full coverage of a sealed type or enum. nullneedscase nullorcase null, default. Without one, the switch throws aNullPointerException.- Record patterns destructure records, possibly nested. They use
varor matching component types and are inferred for generics. - Java 22 added
_unnamed patterns. Primitive patterns are still a preview.
Practice quiz
Test yourself with the pattern matching for switch quiz: 10 exam-style questions with explanations.
Previous: Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
Related reading
- Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
- Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.