Skip to lesson
MentorNxt home

Java Programming

Pattern Matching & Newer Language Features

Guards with when

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

FirstGuardDemo.javaJava
// 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)));    }}
Output
OD-101: free delivery
OD-102: delivery Rs 40
OD-103: delivery Rs 40

What this code does

  • case Order o when o.total() > 500 first checks that the value is an Order, binds o, and then tests the guard. Exactly Rs 500 is not more than 500, so OD-103 falls to the next case.
  • The second case has no guard, so it catches every order the first one rejected. Because Order is a record, that unguarded case also makes the switch complete without default.

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; when is 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

GradeBandDemo.javaJava
// 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));    }}
Output
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 m catches the rest. The first guard rejects impossible marks before any band is given.
  • In bandWrongOrder, 95 stops at m >= 35 and 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

GuardOrderErrorDemo.javaJava
// 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)));    }}
Sample compiler output
GuardOrderErrorDemo.java:8: error: this case label is dominated by a preceding case label
            case Order o when o.total() > 500 -> 0;
                 ^
1 error

What 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 as Number before Integer.
  • 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.

// Java 21
public class Guard {
record Order(String id, double total) { }
static String label(Object o) {
return switch (o) {
case Order x when x.total() > 500 -> "priority";
case Order x -> "normal";
default -> "unknown";
};
}
public static void main(String[] args) {
System.out.println(label(new Order("O-1", 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.

  1. Write one case per row of the rule table: case Express e when e.km() > 20 -> 120;.
  2. Put the stricter guards of a type above its looser ones.
  3. End each type with an unguarded case that covers its remaining values.
  4. Finish with default if the switched type is not sealed.

Example 4 · Delivery charges: if-else chain vs guarded switch

DeliveryChargeDemo.javaJava
// 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));        }    }}
Output
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.
  • Shipment is an ordinary interface, so default is 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

GuardExhaustiveErrorDemo.javaJava
// 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)));    }}
Sample compiler output
GuardExhaustiveErrorDemo.java:6: error: the switch expression does not cover all possible input values
        return switch (order) {
               ^
1 error

What this code does

  • To a person, > 500 and <= 500 cover 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.

Prefer an unguarded last case over adding default. The unguarded case keeps the typed variable, and the compiler still checks the switch.

Next step

Check your understanding

12 quick questions