Sub topic 4
Refining a case with when guards
This chapter assumes you can write a switch expression with type patterns, such as case Integer i ->, and that you know what a record and a sealed interface are. You need JDK 21 or newer. By the end you will be able to add a when guard to a case, predict which case runs, and fix the compile errors that guards commonly cause.
Why a type pattern is sometimes not enough
A type pattern tests only the runtime type of the value. Many decisions also depend on the value's contents: an Integer that is large, a String that is blank, a Circle with radius zero. Without guards you would put an if inside the case body. That works, but the if cannot fall through to the next case. You would have to repeat the fallback logic.
A guard is a boolean condition attached to a pattern label with the keyword when. The case matches only if both the pattern matches and the guard evaluates to true. If the guard is false, the switch moves on to the next case as though this one had not matched.
public class Guards {
static String describe(Object o) {
return switch (o) {
case null -> "null";
case Integer i when i > 100 -> "large int " + i;
case Integer i -> "int " + i;
case String s when s.isBlank() -> "blank string";
case String s -> "string of length " + s.length();
default -> "other: " + o;
};
}
public static void main(String[] args) {
System.out.println(describe(null));
System.out.println(describe(500));
System.out.println(describe(7));
System.out.println(describe(" "));
System.out.println(describe("hello"));
System.out.println(describe(3.14));
}
}Running it prints:
null
large int 500
int 7
blank string
string of length 5
other: 3.14For 500, the first Integer case matches the type and its guard i > 100 is true. For 7, the type matches but the guard is false, so the switch tries the next label, case Integer i, which has no guard and therefore matches.
Syntax and scope
The form is case Pattern when booleanExpression -> result.
- The binding variable (
i,s) is in scope in the guard and in the right-hand side of the arrow. - The guard can be any expression of type
boolean(orBoolean, which is unboxed). It can call methods, use&&and||, and refer to local variables and fields. whenis a contextual keyword. It has special meaning only after a pattern, so existing code that useswhenas an identifier still compiles.- Guards belong to pattern labels only. You cannot write
case 1 when x > 0orcase "a" when ...on constant labels, and you cannot guarddefault.
Java 17 to 20 previewed guards with &&, as in case String s && s.isEmpty(). In Java 21 the final syntax is when. If you copy older examples, translate them.
instanceof has no guard syntax because it does not need one. Use &&: o instanceof String s && !s.isEmpty().
How the switch picks a case
A switch evaluates its case labels from top to bottom and runs the first one that fully matches. For a guarded label, the pattern is tested first and the guard only if the pattern matched. The following example makes that order visible.
public class GuardOrder {
static boolean check(String label, boolean result) {
System.out.println("checking " + label);
return result;
}
static String run(Object o) {
return switch (o) {
case String s when check("long", s.length() > 5) -> "long";
case String s when check("short", s.length() < 3) -> "short";
case String s -> "medium";
default -> "not a string";
};
}
public static void main(String[] args) {
System.out.println(run("abcdefg"));
System.out.println(run("abcd"));
System.out.println(run(42));
}
}The output is:
checking long
long
checking long
checking short
medium
not a stringFor "abcdefg" the first guard succeeds, so the second is never evaluated. For "abcd" both guards run and fail, and the unguarded String case catches it. For 42, no String pattern matches, so no guard runs.
Because guards run in order and can have side effects, keep them pure. A guard that increments a counter or logs a message makes the program depend on case order and on how many labels were tried. This is a readability problem more than a language problem, but it is the usual way guards go wrong in review.
Guards with record patterns
Guards also work after record patterns. The variables bound by the record pattern are available in the guard.
public class Where {
record Point(int x, int y) {}
static String where(Point p) {
return switch (p) {
case Point(var x, var y) when x == 0 && y == 0 -> "origin";
case Point(var x, var y) when x == y -> "diagonal";
case Point p2 -> "point " + p2.x() + "," + p2.y();
};
}
public static void main(String[] args) {
System.out.println(where(new Point(0, 0)));
System.out.println(where(new Point(3, 3)));
System.out.println(where(new Point(1, 2)));
}
}The output is origin, diagonal, then point 1,2. The last case is a plain type pattern with no guard. It matches every Point that the earlier cases rejected, so the switch is exhaustive. The next chapters cover record patterns in more depth. Here they only show that a guard sees the components.
Guards, dominance and exhaustiveness
Guards change two compiler checks.
Dominance. A case label dominates a later one if it would match everything the later one matches. An unguarded pattern dominates any later label for the same type or a subtype. A guarded pattern does not dominate later labels, because the guard might fail. So the order "guarded first, general last" compiles, and the reverse does not.
static String ok(Object o) {
return switch (o) {
case String s when s.isEmpty() -> "empty";
case String s -> "string";
default -> "other";
};
}If you put case String s first, the compiler reports that the guarded String label is dominated and rejects the switch. Always order cases from most specific to most general.
Exhaustiveness. A guarded label is not counted as covering its type, because the compiler does not try to prove what a guard will do. A switch over a sealed hierarchy still needs at least one unguarded label that covers each permitted subtype, or a default. The following code does not compile.
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c when c.radius() > 0 -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
};
}The compiler reports that the switch expression does not cover all possible input values. Circle with a radius of zero or less would match no label. The fix is to add an unguarded case Circle c -> 0;, or to merge the guard into the body.
Two edge cases follow from the same rule. A guard that is the constant true is treated as no guard at all, so it dominates later labels. A guard that is the constant false is a compile-time error, because the label could never match.
| Situation | Result |
|---|---|
| Guarded label before an unguarded label of the same type | Compiles |
| Unguarded label before a guarded label of the same type | Compile error: dominated |
| Only guarded labels cover a sealed subtype | Compile error: not exhaustive |
| Guard is the constant `false` | Compile error |
| Guard throws an exception | Exception propagates from the switch |
| Selector is `null` and there is no `case null` | `NullPointerException` before any guard runs |
Guards and null
A guarded pattern never matches null, because a type pattern does not match null and the guard is not even reached. Without a case null, a null selector throws NullPointerException. You can put case null first, as the first example does, or combine it as case null, default ->. Chapter 3 of this tutorial covers case null in detail.
Common mistakes
- Using
&&instead ofwhen. That was the preview syntax. In Java 21 it is a compile error. - Putting the general case first. The compiler flags every later label for that type as dominated.
- Relying on a guarded case for exhaustiveness. Add an unguarded fallback for each sealed subtype.
- Hiding complex logic in the guard. If a guard needs several lines, move it into a named method, such as
when isEligible(order), and keep the case label readable. - Putting side effects in guards. Guards may run, and fail, before the real case runs.
- Expecting a guard on a constant label.
case 1 when ...is not allowed. Use a pattern such ascase Integer i when i == 1.
Exercise
The following switch does not compile. Give the two reasons it fails and write a version that compiles. Which input would the fixed version send to the default branch?
static String label(Object o) {
return switch (o) {
case Integer i -> "int";
case Integer i when i > 10 -> "big int";
case String s when s.length() > 3 -> "long string";
};
}
Show answer
The second label is dominated: the unguarded case Integer i above it already matches every Integer, so when i > 10 can never be reached. The switch is also not exhaustive for Object: nothing covers other types, and the only String label is guarded. A fixed version is:
static String label(Object o) {
return switch (o) {
case Integer i when i > 10 -> "big int";
case Integer i -> "int";
case String s when s.length() > 3 -> "long string";
default -> "other";
};
}
Strings of length 3 or less, and any value that is neither an Integer nor a String (for example a Double), reach the default branch. A null selector throws NullPointerException unless you add case null.
Exercise
Given record Point(int x, int y) {}, write a switch expression quadrant(Point p) that returns "origin" when both coordinates are zero, "x-axis" or "y-axis" when only one is zero, and "plane" otherwise. Use record patterns with guards and no default.
Show answer
static String quadrant(Point p) {
return switch (p) {
case Point(var x, var y) when x == 0 && y == 0 -> "origin";
case Point(var x, var y) when y == 0 -> "x-axis";
case Point(var x, var y) when x == 0 -> "y-axis";
case Point q -> "plane";
};
}
The last label is an unguarded type pattern for Point, so the switch is exhaustive without default. The origin case must come before the axis cases, because the axis guards also hold at the origin.