A when clause adds a condition to a pattern label, which replaces nested if statements inside each case.
sealed interface Payment permits Card, Upi {}
record Card(int amount) implements Payment {}
record Upi(int amount) implements Payment {}
List<Payment> payments = List.of(new Card(50), new Card(5000), new Upi(200));
for (Payment p : payments) {
String route = switch (p) {
case Card c when c.amount() > 1000 -> "card " + c.amount() + " -> manual review";
case Card c -> "card " + c.amount() + " -> auto approve";
case Upi u -> "upi " + u.amount() + " -> instant";
};
System.out.println(route);
}
card 50 -> auto approve
card 5000 -> manual review
upi 200 -> instant
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30