Pattern Matching for switch in Java 21
Pattern matching for switch is a standard feature in Java 21 (JEP 441), after four previews starting in Java 17. A switch can now test the type of any object, refine matches with when guards, handle null, and check that every case is covered.
This tutorial explains the final syntax, the rules the compiler enforces, and the small additions made in Java 21.
1. Why Is It Needed?
Business rules often depend on the kind of object you have: different events, payments or messages. Long if-else chains with instanceof are hard to read and the compiler cannot tell you when a case is missing. A pattern switch is shorter, returns a value, and becomes exhaustive with sealed types.
2. Syntax
return switch (event) {
case null -> "no event";
case Login l when !l.twoFactor() -> "medium risk"; // guard
case Login l -> "low risk";
case Purchase p -> "check amount " + p.amount();
case Logout lo -> "none";
};
- Labels are checked from top to bottom; a guard with
whenadds a condition. case nullhandles a null selector; without it,nullthrowsNullPointerException.- A label that can never be reached because an earlier one always matches first is a dominance error.
3. Practical Examples
Example 1: Guards, null and sealed types
public class GuardsAndNull {
sealed interface Event permits Login, Purchase, Logout { }
record Login(String user, boolean twoFactor) implements Event { }
record Purchase(String user, double amount) implements Event { }
record Logout(String user) implements Event { }
static String risk(Event e) {
return switch (e) {
case null -> "no event";
case Login l when !l.twoFactor() -> "MEDIUM: " + l.user() + " logged in without 2FA";
case Login l -> "LOW: " + l.user() + " logged in";
case Purchase p when p.amount() > 50_000 -> "HIGH: " + p.user() + " spent " + p.amount();
case Purchase p -> "LOW: purchase by " + p.user();
case Logout lo -> "NONE: " + lo.user() + " logged out";
};
}
public static void main(String[] args) {
Event[] events = { new Login("asha", true), new Login("ravi", false),
new Purchase("meera", 75_000), new Purchase("john", 900), new Logout("asha"), null };
for (Event e : events) {
System.out.println(risk(e));
}
}
}
LOW: asha logged in MEDIUM: ravi logged in without 2FA HIGH: meera spent 75000.0 LOW: purchase by john NONE: asha logged out no event
Example 2: Qualified enum constants
New in Java 21, enum constants can be written with their type name, so one switch can cover constants from two enums that implement the same sealed interface.
public class QualifiedEnums {
sealed interface Command permits Move, Action { }
enum Move implements Command { UP, DOWN }
enum Action implements Command { JUMP, FIRE }
// Java 21: qualified enum constants as case labels, exhaustive over the sealed interface
static String handle(Command c) {
return switch (c) {
case Move.UP -> "moving up";
case Move.DOWN -> "moving down";
case Action.JUMP -> "jumping";
case Action.FIRE -> "firing";
};
}
public static void main(String[] args) {
for (Command c : new Command[] { Move.UP, Action.FIRE, Move.DOWN, Action.JUMP }) {
System.out.println(c + " -> " + handle(c));
}
}
}
UP -> moving up FIRE -> firing DOWN -> moving down JUMP -> jumping
Example 3: A dominated label
public class Dominance {
static String kind(Object o) {
return switch (o) {
case CharSequence cs -> "char sequence";
case String s -> "string"; // never reachable: String is a CharSequence
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(kind("x"));
}
}
Dominance.java:5: error: this case label is dominated by a preceding case label
case String s -> "string"; // never reachable: String is a CharSequence
^
1 error
4. How the Compiler Checks a Pattern Switch
5. Important Points and Best Practices
- Prefer sealed types and no
default, so adding a subtype produces compile errors everywhere it must be handled. - Put guarded labels before the unguarded label of the same type.
- Keep guards simple and free of side effects.
- If no
case nullexists, the switch still throwsNullPointerExceptionfornull. - Java 22 added unnamed patterns (
_) for components you want to ignore.
6. Summary
- Pattern matching for
switchis final in Java 21 (JEP 441). - Labels can be type patterns, record patterns,
case nulland qualified enum constants. whenguards refine a pattern.- The compiler checks dominance and exhaustiveness.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. Is pattern matching for switch final in Java 21?
Yes. JEP 441 made it a standard feature in Java 21, after previews in Java 17, 18, 19 and 20.
Q2. What is a when guard?
A boolean condition after a pattern, such as case Purchase p when p.amount() > 50000. The case matches only if the pattern matches and the condition is true.
Q3. What is a dominated case label?
A label that can never be selected because an earlier label always matches first, for example case String s after case CharSequence cs. It is a compile error.
Q4. Does a pattern switch need a default branch?
Not when it is exhaustive, for example when it covers every permitted subtype of a sealed interface.