Sub topic 14
Where This Leads: Patterns in switch
This chapter assumes you can write instanceof type patterns with binding variables, know how && and ! control a binding's scope, and have met records and sealed types. It shows how the same ideas appear in switch. Pattern matching for switch is final in Java 21. Type patterns in instanceof have been final since Java 16, and record patterns are final in Java 21. Earlier releases only offer switch patterns as a preview feature.
From an if-chain to a switch
Code that handles several possible types often becomes a chain of instanceof tests:
static String describe(Object o) {
if (o instanceof Integer i) {
return "int " + i;
} else if (o instanceof String s) {
return "string of length " + s.length();
} else {
return "something else";
}
}Each test uses a type pattern, and the chain works. But the reader has to scan every if to see that one value is being classified, and the compiler cannot check whether you covered every case. A switch states the intent directly:
static String describe(Object o) {
return switch (o) {
case Integer i -> "int " + i;
case String s -> "string of length " + s.length();
default -> "something else";
};
}In each case, the pattern Integer i is the same type pattern you used after instanceof. The label matches when the selector value is an Integer. In that case, the binding variable i is declared with type Integer, and the code after the arrow can use it.
What a case label can contain
Before Java 21, a case label held only a constant: an integer, a string, or an enum name. Now a label can also hold:
- A type pattern such as
String s. - A record pattern such as
Circle(double r). - The literal
null, writtencase null. - A pattern followed by a guard, written
when condition.
The selector expression can have any reference type, not just int, String, or an enum. This is what lets switch replace the instanceof chain.
Guards replace && inside a case
With instanceof, you add a condition with &&, for example o instanceof String s && s.length() > 10. A case label has no && for this purpose. You add the extra condition with when:
static String classify(Object o) {
return switch (o) {
case String s when s.length() > 10 -> "long string";
case String s -> "short string";
default -> "not a string";
};
}The binding s is in scope inside the when expression, in the same way that it is in scope on the right of &&. If the guard evaluates to false, the switch does not take that branch. It continues with the next label, so the second case String s handles the strings that were not long.
Order matters: dominance
The compiler tests labels from top to bottom, and the first match wins. Because of this, a label that can never be reached is a compile-time error, not a warning. A label is dominated when an earlier label already matches everything it would match.
static String broken(Object o) {
return switch (o) {
case CharSequence cs -> "chars";
case String s -> "string"; // error: this label is dominated
default -> "other";
};
}String implements CharSequence, so any string is caught by the first label. Put the more specific pattern first and the general one after it. A guarded pattern does not dominate a later, narrower pattern, because the guard may fail. An unguarded pattern does dominate later ones.
static String order(Object o) {
return switch (o) {
case Integer i when i > 100 -> "big";
case Integer i -> "small";
default -> "other";
};
}This compiles because the guarded label comes first. If you swapped the two Integer labels, the guarded label would be dominated and the code would not compile.
How a switch evaluates a value
The following diagram shows the steps for a pattern switch.
Null handling differs from instanceof
This is the main behavioral difference from the instanceof form. o instanceof String s is simply false when o is null. A switch over a reference type has historically thrown NullPointerException for a null selector, and that behavior remains unless you opt out. You opt out by writing a case null label:
static String safe(Object o) {
return switch (o) {
case null -> "no value";
case String s -> "string " + s;
default -> "other";
};
}Without case null, safe(null) would throw. You can also combine the two as case null, default -> when both should share a branch. No type pattern ever matches null, in either instanceof or switch. The switch simply checks for null first and makes you decide what to do.
Exhaustiveness and sealed types
A switch expression must produce a value for every possible input. A pattern switch statement must also cover all cases. When the selector's type is Object, you need a default or an unconditional pattern such as case Object x. When the selector is a sealed type, the compiler knows every permitted subtype, so it can verify full coverage without default.
Here is a complete program that combines sealed types, record patterns, and a switch:
public class Main {
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rectangle(double w, double h) -> w * h;
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(1.0)));
System.out.println(area(new Rectangle(2.0, 3.0)));
}
}There is no default. If you later add a third record to the permits list, area stops compiling until you add a case for it. This is the advantage over an if/else chain, which would silently fall through to a final else. Avoid adding a default to a switch over a sealed type unless you really want it, because it hides that compile-time reminder.
Record patterns nest, so case Rectangle(double w, double h) tests the type and extracts the components in one step, as the previous chapter showed for instanceof. The same is true for enums and for sealed hierarchies of any depth: the compiler checks every combination.
Scope of bindings in a switch
Flow scoping still applies, in a simpler form. A binding declared in a case label is in scope in that label's guard and in its branch, and nowhere else.
- Two different labels can reuse the name
s, as the earlier examples did, because the scopes do not overlap. - With the arrow form (
->), there is no fall-through, so each branch is independent. - With the old colon form (
case String s:), falling through from a label that declares a binding into another label is a compile-time error, because the next branch could not rely on the binding being set.
You do not need the negation trick from the early-return guard here. In instanceof, you wrote if (!(o instanceof String s)) return -1; to keep s in scope afterwards. In a switch, the matching branch contains its own code, so you place the logic after the arrow.
Choosing between if and switch
| Situation | Better choice |
|---|---|
| One type test with a single follow-up action | `if (x instanceof T t)` |
| Extra boolean conditions on one value | `instanceof` with `&&`, or `case` with `when` |
| Many types handled in parallel | `switch` with patterns |
| Sealed hierarchy where every subtype needs handling | `switch` without `default` |
| A null selector needs a specific result | `switch` with `case null` |
| `equals` implementation | `instanceof` with `&&` |
Common mistakes
- Putting a general pattern above a specific one, which causes a "dominated label" error.
- Forgetting
case nulland getting aNullPointerExceptionfrom aswitchthat previously worked as aninstanceofchain. - Writing
case String s && s.isEmpty(). Usewhen s.isEmpty()instead. - Adding
defaultto a sealed-type switch and losing the exhaustiveness check. - Running on Java 17 or earlier and seeing errors on pattern labels. Check the version with
java -version, and make sure that the compiler's--releaseflag is 21 or higher.
Exercises
Exercise
Why does this method fail to compile, and how do you fix it? static String f(Object o) { return switch (o) { case Number n -> "number"; case Integer i -> "integer"; default -> "other"; }; }
Show answer
Number is a supertype of Integer, so the first label matches every Integer and the second label is dominated, which is a compile-time error. Fix it by putting case Integer i before case Number n.
Exercise
What does each call return? static String g(Object o) { return switch (o) { case null -> "null"; case String s when s.isEmpty() -> "empty"; case String s -> "text"; default -> "other"; }; } g(null), g(""), g("hi"), g(5)
Show answer
g(null) returns "null" because of the case null label. g("") returns "empty" because the guard is true. g("hi") returns "text" because the guard fails and the next String label matches. g(5) returns "other" through the default branch.
Exercise
A switch over a sealed interface Shape has no default. A teammate adds a new record Triangle to the permits list. What happens to the switch, and why is that useful?
Show answer
The switch no longer compiles, because it is not exhaustive. The compiler reports the missing case, so you must handle Triangle before the code builds. An if/else chain would have handled the new type with its final else branch, perhaps incorrectly and without warning.