Java Pattern Matching: switch Patterns, Record Patterns and Guards
Master pattern matching for switch (Java 21+): type patterns, record patterns, unnamed variables, case null, guards with when, exhaustiveness rules, dominance, constant labels, MatchException, and scope and fall-through rules, with runnable examples.
kvi5hnuCode Sprout team member10 min readOn this page
You've seen instanceof with a pattern variable in the casting article, and an exhaustive switch over a sealed type. This article covers pattern matching for switch systematically. It's final since Java 21 and one of the most important modern Java features. The everyday use is easy to learn. The finer rules (null handling, dominance, exhaustiveness) exist mostly so that old switch code keeps its meaning, and they are worth knowing before they surprise you.
From instanceof Chains to switch
Classifying an employee with instanceof patterns looks like this:
Employee e = . . .;
String description;
if (e instanceof Director dir)
description = "A director with a title of " + dir.getTitle();
else if (e instanceof Manager m)
description = "A manager, eligible for a bonus";
else
description = "A staff member earning " + e.getSalary();
The pattern-matching form of switch simplifies this type analysis:
String description = switch (e) {
case Director dir -> "A director with a title of " + dir.getTitle();
case Manager m -> "A manager, eligible for a bonus";
default -> "A staff member earning " + e.getSalary();
};
As with instanceof, each case declares a pattern variable of the matched type, which you use to call subclass methods such as getTitle.
The switch expression yields a value that's assigned once. With the if chain, every branch must set description separately (and the compiler can't easily check that none is missed). You can also use type patterns in switch statements, including the fall-through form with colons, but the expression form without fall-through is usually the most natural.
Unnamed variables: _
If you don't need the pattern variable, write an underscore (unnamed variables were a preview in Java 21 and are final since Java 22, JEP 456):
case Employee _ -> "A staff member"
Before Java 22, people used a dummy name like __. A single _ has been a reserved word since Java 9, which is what made this feature possible.
Null Handling
The classic switch is null-hostile: if the selector is null, it throws a NullPointerException. With pattern matching, you can handle null explicitly with case null:
String description = switch (e) {
case Director dir -> "A director with a title of " + dir.getTitle();
case Manager m -> "A manager, eligible for a bonus";
case null -> "No employee";
default -> "A staff member earning " + e.getSalary();
};
case null can be combined with default, but with no other case:
case null, default -> "unknown";
There's deliberately no case _ as a catch-all: you'd have to remember whether it covers null or not. Without case null, a null selector still throws NullPointerException, even in a pattern switch.
Guards
Add a condition to a pattern with a guard, introduced by the contextual keyword when:
case Director dir when dir.getTitle().length() >= 20 -> "A director with a long title";
The guard can use the pattern variable. If the guard is false, the case isn't selected and the next case is tried. If the guard throws an exception, the switch throws that exception.

Record Patterns
A record pattern matches a record and deconstructs it into its components, which can be nested patterns themselves (Java 21). Guards are particularly useful with record patterns:
record Reading(String sensor, double celsius) { }
String alert = switch (r) {
case Reading(var name, var t) when t < 0 -> name + ": frost";
case Reading(_, var t) when t > 35 -> "heat warning";
case Reading(var name, _) when name.startsWith("test") -> "ignored";
default -> "normal";
};
Notes:
- Use
varor explicit types for the components:Reading(String name, double t). - Nesting works:
case Trip(Stop(var from, _), Stop(var to, _)) -> .... - A record pattern calls the record's accessor methods. If a custom accessor throws an exception, the
switchthrows aMatchExceptionthat wraps it. This can only happen with hand-written accessors. - Generic records can be matched with or without type arguments:
case Box(String s)infersBox<String>.
Exhaustiveness
A switch expression must be exhaustive: there must be a case for every possible selector value, since the expression must always yield something. A switch is exhaustive if it has:
- cases for every constant of an enum,
- unguarded type patterns covering every permitted subtype of a sealed type,
- an unguarded type pattern of the selector's type itself (e.g.
case Employee e), or - a
defaultclause.
Guarded patterns don't count toward exhaustiveness, because the compiler can't evaluate guards. These two cases aren't exhaustive, even though one of the conditions is always true:
case Director dir when dir.getTitle().length() >= 20 -> . . .
case Director dir when dir.getTitle().length() < 20 -> . . .
Rewrite the second as an unguarded case Director dir -> or add default.
If a sealed hierarchy or an enum is changed after a switch was compiled, a previously exhaustive switch may meet a value no case covers. Then it throws a MatchException instead of silently doing nothing. (Since Java 21 this also applies to enum switches, which threw IncompatibleClassChangeError before.)
Enhanced switch statements must be exhaustive too
A classic switch statement needn't be exhaustive: if nothing matches, nothing happens. For clarity, enhanced switch statements must be exhaustive. A switch statement is enhanced if it uses a pattern or case null, or if its selector type isn't one of the classic types (a primitive, a primitive wrapper, String or an enum):
switch (obj) { case String s -> { } } // error: the switch statement does not cover all possible input values
If you don't want to do anything for other values, add an empty default:
default -> {} // arrow form
default: break; // colon form
Dominance: Order Matters
In a classic switch with constant cases, the same constant can't appear twice, so cases are disjoint and their order doesn't matter. With patterns, order matters. Cases are checked top to bottom and the first match wins. If a case can never match because an earlier one always matches first, that's a compile-time error:
String description = switch (e) {
case Employee _ -> "A staff member";
case Manager m -> "A manager"; // error: this case label is dominated by a preceding case label
};
Every Manager is an Employee, so the first case dominates the second. Put more specific cases before more general ones.
The checking isn't perfect:
- Guarded patterns aren't used in dominance checking. The compiler can't tell that
case Director dir when dir.getTitle().length() >= 10dominates a latercase Director dir when dir.getTitle().length() >= 20. defaultdoesn't dominate constant cases, anddefaultdoes dominatecase null, even though it doesn't cover it.
Patterns and Constants
You can't match constants inside record patterns:
case Reading("roof", var t) -> . . . // syntax error
case Reading(var s, var t) when s.equals("roof") -> . . . // OK: use a guard
Constant case labels follow the old rules for their types:
- Numeric constants are only allowed when the selector type is
int,short,charorbyte, or their wrappers. - String constants are only allowed for a selector of type
String.
So with an Object selector, this is illegal:
Object obj = . . .;
String description = switch (obj) {
case 0 -> "zero"; // error: constant label of type int is not compatible with switch selector type Object
case "" -> "empty string"; // error: constant label of type String is not compatible ...
case null -> "null";
default -> obj.toString();
};
The remedy is type patterns with guards:
case Integer i when i == 0 -> "zero";
case String s when s.isEmpty() -> "empty string";
Enum constants are more relaxed: the selector type just has to be a supertype of the enum (Object, Enum, or an interface the enum implements), and you write the qualified name:
Object obj = . . .;
String description = switch (obj) {
case DayOfWeek.FRIDAY -> "TGIF"; // OK
. . .
};
Variable Scope and Fall-Through
This section covers subtle points about the colon form with fall-through. If you only use -> cases, you can skip it.
The scope of a pattern variable extends to the end of its case, including the guard and the statements after the colon. It doesn't extend into the next case, because execution can start there when the first pattern didn't match:
switch (obj) {
case String s when s.isEmpty(): System.out.println("empty " + s); // s usable here
default: System.out.println(obj); // but not here
}
You can't fall into a type pattern that declares a variable. If execution fell from the first case into the second, n couldn't be bound:
switch (obj) {
case String s when s.length() > 0: System.out.println(s);
case Integer n: System.out.println(n); // error: illegal fall-through to a pattern
. . .
}
With an unnamed pattern, falling through is fine, since nothing needs to be bound: case String _: System.out.println("string");.
A Complete Example
import java.time.DayOfWeek;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static void main(String[] args) {
Employee[] staff = {
new Employee("Omar Haddad", 52000),
new Manager("Priya Nair", 91000),
new Director("Noor Saleh", 120000, "Chief Technology Officer"),
new Director("Ada Lee", 110000, "CTO"),
null
};
for (Employee e : staff) {
System.out.println(describe(e));
}
for (Reading r : List.of(new Reading("roof", -2.5), new Reading("yard", 38),
new Reading("test-1", 20), new Reading("hall", 21))) {
System.out.println(r + " " + alert(r));
}
for (Object o : new Object[] {0, 42, "", "hi", DayOfWeek.FRIDAY, 3.5, null}) {
System.out.println(classify(o));
}
Box<Box<String>> doubleBoxed = new Box<>(new Box<>("gift"));
System.out.println(unbox(doubleBoxed));
System.out.println(unbox(new Box<>(new Box<>(null))));
try {
unbox(new Box<>(null));
} catch (MatchException ex) {
System.out.println("MatchException");
}
}
static String describe(Employee e) {
return switch (e) {
case Director dir when dir.getTitle().length() >= 20 ->
"A director with a long title";
case Director dir ->
"A director with a title of " + dir.getTitle();
case Manager m -> {
m.setBonus(10000);
yield "A manager who just got a bonus";
}
case null -> "No employee";
default -> "A staff member earning " + e.getSalary();
};
}
static String alert(Reading r) {
return switch (r) {
case Reading(var name, var t) when t < 0 -> name + ": frost";
case Reading(_, var t) when t > 35 -> "heat warning";
case Reading(var name, _) when name.startsWith("test") -> "ignored";
default -> "normal";
};
}
static String classify(Object obj) {
return switch (obj) {
case Integer i when i == 0 -> "zero";
case Integer i -> "int " + i;
case String s when s.isEmpty() -> "empty string";
case String s -> "string " + s;
case DayOfWeek.FRIDAY -> "TGIF";
case null -> "null";
default -> "something else: " + obj;
};
}
static String unbox(Box<Box<String>> b) {
return switch (b) {
case Box(Box(String s)) -> s;
};
}
}
record Reading(String sensor, double celsius) { }
record Box<T>(T contents) { }
class Employee {
private final String name;
private final double salary;
Employee(String name, double salary) { this.name = name; this.salary = salary; }
public String getName() { return name; }
public double getSalary() { return salary; }
}
class Manager extends Employee {
private double bonus;
Manager(String name, double salary) { super(name, salary); }
public void setBonus(double bonus) { this.bonus = bonus; }
@Override public double getSalary() { return super.getSalary() + bonus; }
}
class Director extends Manager {
private final String title;
Director(String name, double salary, String title) { super(name, salary); this.title = title; }
public String getTitle() { return title; }
}
A staff member earning 52000.0
A manager who just got a bonus
A director with a long title
A director with a title of CTO
No employee
Reading[sensor=roof, celsius=-2.5] roof: frost
Reading[sensor=yard, celsius=38.0] heat warning
Reading[sensor=test-1, celsius=20.0] ignored
Reading[sensor=hall, celsius=21.0] normal
zero
int 42
empty string
string hi
TGIF
something else: 3.5
null
gift
null
MatchException
The Manager case uses a block with yield to produce its value after a side effect (see switch expressions).
Common questions
Does a pattern switch replace the visitor pattern?
For sealed hierarchies, largely yes. A switch with type or record patterns is shorter than double dispatch with accept and visit methods, and the compiler checks exhaustiveness. Visitors still make sense for open hierarchies, or when the operation must live inside the class hierarchy for some reason.
Why is case null not covered by default?
For compatibility. Classic switches always threw on null, and silently routing null into an existing default would change the behaviour of old code. If you want null to go to the default branch, write case null, default ->.
Can I use instanceof with a record pattern?
Yes: if (shape instanceof Rectangle(var w, var h) && w == h). Record patterns work in both instanceof and switch, and they can be nested.
What is a MatchException?
It is thrown when an exhaustive pattern switch meets a value that no case covers at runtime. That can happen because a sealed hierarchy or an enum changed after compilation, or because a null record component didn't match a nested pattern. It also wraps exceptions thrown by record accessors during matching.
Can patterns test primitive values like case int i when i > 0?
Not in final Java yet. Primitive patterns have been a preview feature since Java 23 (fifth preview in Java 27, JEP 532). Until they're final, switch on the wrapper with type patterns and guards (case Integer i when i > 0), or use if statements.
Summary
switchcan match type patterns (case Manager m), record patterns (case Reading(var s, var t)), constants, andnull. Use_for unneeded variables (Java 22+).case nullhandles null selectors. Without it,nullthrowsNullPointerException.case null, defaultcombines both.- Guards (
when) add conditions. A false guard moves on to the next case. - Switch expressions, and enhanced switch statements, must be exhaustive: all enum constants, all subtypes of a sealed type, an unguarded pattern of the selector type, or
default. Guarded cases don't count. Mismatches at runtime throwMatchException. - Cases are tried in order. Dominated cases are compile errors, so put specific cases first and
defaultlast. - No constants inside record patterns (use guards). Numeric and string constants need matching selector types; enum constants work with any supertype.
- Pattern variables are scoped to their case. You can't fall through into a pattern that binds a variable.
Practice Questions
Rewrite as a switch expression: if (o instanceof Integer i) r = i * 2; else if (o instanceof String s) r = s.length(); else r = -1;
int r = switch (o) {
case Integer i -> i * 2;
case String s -> s.length();
default -> -1;
};
What does switch (e) { case Manager m -> "M"; default -> "E"; } do when e is null?
It throws a NullPointerException. Add case null -> ... (or case null, default -> ...) to handle it.
Why is this switch rejected? switch (shape) { case Shape s -> "any"; case Circle c -> "circle"; }
case Shape s matches every shape, so case Circle c can never be reached. It's dominated, which is a compile error. Put Circle first.
A sealed interface has permitted Circle and Square. Is switch (s) { case Circle c when c.r() > 0 -> 1; case Square q -> 2; } exhaustive?
No. The Circle case is guarded, and guarded cases don't count toward exhaustiveness. Add an unguarded case Circle c -> ... or a default.
How do you match a Reading from sensor "roof" in a switch, given that case Reading("roof", var t) isn't allowed?
Use a guard: case Reading(var s, var t) when s.equals("roof") -> ....
With an Object selector, why is case "yes" -> ... an error, while case DayOfWeek.MONDAY -> ... is fine?
String constant labels require a String selector. Enum constant labels only need the selector type to be a supertype of the enum, and Object is. For the string, write case String s when s.equals("yes") -> ....
Previous: Java Sealed Classes and Interfaces: Controlling Inheritance
Next: Java Reflection: The Class Class, Exceptions Primer and Loading Resources
Related reading
- Java Sealed Classes and Interfaces: Controlling Inheritance
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
- Java Variables, Constants, var and final Explained
- Java Enum Classes: Enumerated Types with Fields and Methods

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.