Switch patterns and exhaustiveness
What you will learn
Pattern matching for switch selects a branch using the runtime type and, optionally, the components of an object. For a sealed hierarchy, Java can check that the alternatives are covered at compile time. This is useful when one operation must translate every modeled outcome into a result, such as a message or a status.
- Write an exhaustive Java 21 pattern switch over a sealed hierarchy with a deliberate null policy.
- Order guarded and unguarded cases correctly and diagnose dominance or missing-case errors.
Use a fresh folder for each complete Main.java example. Compile with javac --release 21 Main.java and run java Main. Requires JDK 21 or a compatible newer JDK. The examples use the standard library only.
Translate every review outcome
public class Main { sealed interface Review permits Accepted, Rejected {} record Accepted(int count) implements Review {} record Rejected(String reason) implements Review {} static String message(Review review) { return switch (review) { case Accepted(int count) -> "Accepted: " + count; case Rejected(String reason) -> "Rejected: " + reason; case null -> "Missing review"; }; } public static void main(String[] args) { System.out.println(message(new Accepted(2))); System.out.println(message(new Rejected("Incomplete"))); System.out.println(message(null)); }}Expected output:
Accepted: 2Rejected: IncompleteMissing reviewBoth permitted variants are handled, so no default is necessary. A new permitted variant requires this source to be reconsidered when recompiled. case null handles a missing selector explicitly. The record patterns extract their data without explicit casts.
Rules and mental model
Pattern switch and record patterns are permanent in Java 21. Switch expressions must be exhaustive; enhanced switch statements (such as those using patterns or case null) also need exhaustive coverage. A sealed root can make a default unnecessary when all applicable permitted branches are covered. A guarded case normally does not count toward exhaustive coverage unless the guard is a constant expression that is true. Dominance is a compile-time reachability rule: a broad unguarded case before a narrower one can make the latter illegal. Put narrow cases first. Null is separate: absent case null, a null selector throws NullPointerException even with default. Exhaustiveness is a static type-coverage property, not a guarantee every runtime value will match. For example, a nested record pattern may fail on a null component; if no label applies in an otherwise exhaustive switch, a MatchException can result. Separate compilation and later changes to a sealed hierarchy can also lead to MatchException. Choose a default only when you have a meaningful fallback policy. No preview primitive type patterns are used here; int components of records are supported by Java 21 record patterns.
Place a specific guarded case before its general case
public class Main { static String label(Object value) { return switch (value) { case null -> "missing"; case String s when s.isBlank() -> "blank"; case String s -> "text:" + s; case Integer n when n < 0 -> "negative"; case Integer n -> "number:" + n; default -> "other"; }; } public static void main(String[] args) { for (Object x : new Object[] {" ", "Map", -1, 0, true, null}) { System.out.println(label(x)); } }}Expected output:
blanktext:Mapnegativenumber:0othermissingA when guard is tested only after its pattern matches. If it is false, the search continues. The unguarded String branch covers all remaining strings. Reversing the String cases would make the guarded case dominated and fail compilation. default handles other non-null values.
Handle a reopened branch as a type
public class Main { sealed interface Message permits Plain, Extension {} record Plain(String text) implements Message {} static non-sealed class Extension implements Message {} static final class Reminder extends Extension {} static String category(Message message) { return switch (message) { case Plain p -> "plain"; case Extension e -> "extension"; case null -> "missing"; }; } public static void main(String[] args) { System.out.println(category(new Plain("Hello"))); System.out.println(category(new Extension())); System.out.println(category(new Reminder())); }}Expected output:
plainextensionextensionThe Extension type pattern covers its current and future descendants. Listing only Reminder would not cover Extension itself or its other possible descendants. This switch remains exhaustive without needing to enumerate every concrete class.
Common mistakes
Avoid putting case Object o before case String s, or using only a guarded String case when other strings remain possible. A default is not a null handler. For a closed business model, a catch-all default can hide a newly introduced variant on recompilation; prefer explicitly handling the known alternatives unless a genuine fallback is required.
Practice
Create a sealed interface Pickup with records Ready(int shelf) and Delayed(int days). Write message(Pickup) as a switch expression. A positive shelf returns shelf N; other Ready values return invalid shelf. A Delayed value returns wait N, and null returns missing. Test positive shelf, zero shelf, a delay and null.
Check your result with the chapter practice task and explain why it works.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Switch patterns and exhaustiveness — knowledge check
Apply sealing, flow scope and pattern switch rules using Java 21-compatible examples.
Which branch handles the value " " in label?
What if case String s precedes case String s when s.isBlank()?
What happens for a null selector with default but no case null?
Why does the Message switch cover Reminder?
What happens if a new permitted record is added and the closed Review switch is recompiled unchanged?