Guards with when
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A guard is an extra condition on a pattern case, written with when: case Order o when o.total() > 500 ->. The case matches only if the type matches and the condition is true. Guards are part of Java 21 pattern matching for switch.
Java 21: case Order o when o.total() > 500 ->
A type pattern alone answers one question: what type is this value? Real rules ask more. An order over Rs 500 gets free delivery; a short Express trip costs less than a long one.
Example 1 · A first guard: free delivery above Rs 500
// Java 21record Order(String id, double total) { }
public class FirstGuardDemo { static String delivery(Order order) { return switch (order) { case Order o when o.total() > 500 -> o.id() + ": free delivery"; case Order o -> o.id() + ": delivery Rs 40"; }; }
public static void main(String[] args) { System.out.println(delivery(new Order("OD-101", 749.0))); System.out.println(delivery(new Order("OD-102", 320.0))); System.out.println(delivery(new Order("OD-103", 500.0))); }}OD-101: free delivery OD-102: delivery Rs 40 OD-103: delivery Rs 40
What this code does
case Order o when o.total() > 500first checks that the value is anOrder, bindso, and then tests the guard. Exactly Rs 500 is not more than 500, soOD-103falls to the next case.- The second case has no guard, so it catches every order the first one rejected. Because
Orderis a record, that unguarded case also makes the switch complete withoutdefault.
Before guards, you matched the type and then wrote an if inside the case.
With when, the condition sits on the case label itself. The pattern runs first and binds its variable; then the guard is checked using that variable. If the guard is false, Java moves on to the next case as if this one did not match.
A guard can be any boolean expression: when o.total() > 500 && o.isPrepaid(). Local variables from outside the switch can be used in a guard only if they are effectively final, which means they are never changed after they get their first value.
case Order o when o.total() > 500 -> "free delivery";case Integer m when m >= 35 -> "pass";case String s when s.isBlank() -> "empty input";- Guards need Java 21;
whenis a keyword only inside a case label.
Ordering guarded and unguarded cases
Cases are still tried from top to bottom. A guarded case must come before the unguarded case of the same type.
Example 2 · Guards on ranges: strictest first
// Java 21public class GradeBandDemo { static String band(Object value) { return switch (value) { case Integer m when m < 0 || m > 100 -> "invalid marks"; case Integer m when m >= 90 -> "A+"; case Integer m when m >= 75 -> "A"; case Integer m when m >= 35 -> "Pass"; case Integer m -> "Fail"; case String s when s.equals("AB") -> "Absent"; default -> "Unknown entry"; }; }
static String bandWrongOrder(Object value) { return switch (value) { case Integer m when m >= 35 -> "Pass"; case Integer m when m >= 90 -> "A+"; case Integer m -> "Fail"; default -> "Unknown entry"; }; }
public static void main(String[] args) { Object[] marks = {95, 81, 47, 12, 140, "AB", 3.5}; for (Object m : marks) { System.out.println(m + " -> " + band(m)); } System.out.println("Wrong order, 95 -> " + bandWrongOrder(95)); }}95 -> A+ 81 -> A 47 -> Pass 12 -> Fail 140 -> invalid marks AB -> Absent 3.5 -> Unknown entry Wrong order, 95 -> Pass
What this code does
- The guards go from strictest to loosest, and the unguarded
case Integer mcatches the rest. The first guard rejects impossible marks before any band is given. - In
bandWrongOrder, 95 stops atm >= 35and the A+ case is never reached. The compiler does not warn about this, because it cannot compare guard conditions; the order is your job.
Example 3 · Mistake: the unguarded case comes first
// Java 21record Order(String id, double total) { }
public class GuardOrderErrorDemo { static int charge(Order order) { return switch (order) { case Order o -> 40; case Order o when o.total() > 500 -> 0; }; }
public static void main(String[] args) { System.out.println(charge(new Order("OD-1", 900))); }}GuardOrderErrorDemo.java:8: error: this case label is dominated by a preceding case label
case Order o when o.total() > 500 -> 0;
^
1 errorWhat this code does
case Order o ->matches every order, so the guarded case below it could never run. Java reports it as dominated, the same error asNumberbeforeInteger.- Swap the two cases: the guarded case first, the unguarded one last.
case Order o -> matches every order, so a case Order o when ... placed after it could never run; the compiler reports it as dominated.
Among guarded cases of the same type, the compiler does not check the order, because it cannot know which conditions overlap. If when m >= 35 comes before when m >= 90, a score of 95 stops at the first case and gets the wrong band. The code compiles and gives a wrong answer.
So write range guards from the strictest to the loosest, like the rungs of a ladder: 90 and above, then 75 and above, then 35 and above, then everyone else.
Predict the output
Which case wins?
Read each program and pick the output. Cases are tried from top to bottom.
Round 1 of 3
An order of Rs. 750.
Replacing a long if-else chain
Delivery charges are a typical rule table. Store pickup is free. Standard delivery is free from Rs 499, otherwise Rs 40. Express costs Rs 80 up to 20 km and Rs 120 beyond.
- Write one case per row of the rule table:
case Express e when e.km() > 20 -> 120;. - Put the stricter guards of a type above its looser ones.
- End each type with an unguarded case that covers its remaining values.
- Finish with
defaultif the switched type is not sealed.
Example 4 · Delivery charges: if-else chain vs guarded switch
// Java 21import java.util.List;
interface Shipment { }
record StorePickup(double total) implements Shipment { }
record Standard(double total, int km) implements Shipment { }
record Express(double total, int km) implements Shipment { }
public class DeliveryChargeDemo { static int chargeOld(Shipment s) { if (s instanceof StorePickup) { return 0; } else if (s instanceof Standard st && st.total() >= 499) { return 0; } else if (s instanceof Standard) { return 40; } else if (s instanceof Express ex && ex.km() > 20) { return 120; } else if (s instanceof Express) { return 80; } throw new IllegalArgumentException("Unknown shipment"); }
static int charge(Shipment s) { return switch (s) { case StorePickup p -> 0; case Standard st when st.total() >= 499 -> 0; case Standard st -> 40; case Express ex when ex.km() > 20 -> 120; case Express ex -> 80; default -> throw new IllegalArgumentException("Unknown shipment"); }; }
public static void main(String[] args) { List<Shipment> cart = List.of( new StorePickup(250), new Standard(650, 8), new Standard(300, 8), new Express(300, 35), new Express(1200, 6)); for (Shipment s : cart) { System.out.println(s + " -> old Rs " + chargeOld(s) + ", new Rs " + charge(s)); } }}StorePickup[total=250.0] -> old Rs 0, new Rs 0 Standard[total=650.0, km=8] -> old Rs 0, new Rs 0 Standard[total=300.0, km=8] -> old Rs 40, new Rs 40 Express[total=300.0, km=35] -> old Rs 120, new Rs 120 Express[total=1200.0, km=6] -> old Rs 80, new Rs 80
What this code does
- Both methods give the same charges, but the switch reads like the rule table: one line per rule, type first, condition second, charge last.
Shipmentis an ordinary interface, sodefaultis still needed. Notice how each type ends with an unguarded case for the values its guards did not take.
As an if-else chain, every branch repeats an instanceof check, a cast and a condition, and the rules hide inside the noise.
As a guarded switch, each rule is one line: type, condition, charge. You can read it top to bottom like the price list on a website. Adding a new rule means adding one case in the right place.
Trap: a guarded case does not count toward exhaustiveness
The compiler never evaluates your guards. To it, when o.total() > 500 and when o.total() <= 500 are two unknown conditions, even though together they clearly cover every order.
Example 5 · Trap: only guarded cases, so not exhaustive
// Java 21record Order(String id, double total) { }
public class GuardExhaustiveErrorDemo { static String tier(Order order) { return switch (order) { case Order o when o.total() > 500 -> "free delivery"; case Order o when o.total() <= 500 -> "paid delivery"; }; }
public static void main(String[] args) { System.out.println(tier(new Order("OD-9", 120))); }}GuardExhaustiveErrorDemo.java:6: error: the switch expression does not cover all possible input values
return switch (order) {
^
1 errorWhat this code does
- To a person,
> 500and<= 500cover every order. The compiler does not evaluate guards, so it sees two cases that might both fail, and the switch is not complete. - Remove the second guard:
case Order o -> "paid delivery";. An unguarded last case always makes that type complete.
So a switch whose only Order cases are guarded is not exhaustive, and it fails with "the switch expression does not cover all possible input values". The fix is simple: make the last case for each type unguarded (case Order o ->). It catches whatever the guards above it did not.
default. The unguarded case keeps the typed variable, and the compiler still checks the switch.Next step
Check your understanding
12 quick questions