Exhaustive switch and case null
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A payment can be Card, UPI or Cash. If a new type is added later, a switch with a default quietly ignores it, and a bug slips through.
Java 21: no default when every sealed subtype is covered
A switch is exhaustive when its cases cover every possible value, such as every subtype of a sealed interface, so no default branch is needed.
A sealed interface names all the types allowed to implement it: sealed interface Payment permits Upi, Card, Cash. No other class can join without changing that line. So the compiler knows there are exactly three kinds of Payment.
Example 1 · A sealed Payment and a switch with no default
// Java 21import java.util.List;
sealed interface Payment permits Upi, Card, Cash { }
record Upi(String vpa, int amount) implements Payment { }
record Card(String last4, int amount) implements Payment { }
record Cash(int amount) implements Payment { }
public class SealedSwitchDemo { static int fee(Payment p) { return switch (p) { case Upi u -> 0; case Card c -> c.amount() * 2 / 100; case Cash c -> 0; }; }
static String label(Payment p) { return switch (p) { case Upi u -> "UPI " + u.vpa(); case Card c -> "Card *" + c.last4(); case Cash c -> "Cash"; }; }
public static void main(String[] args) { List<Payment> today = List.of(new Upi("meera@okbank", 640), new Card("9012", 2500), new Cash(150)); int fees = 0; for (Payment p : today) { System.out.println(label(p) + " -> fee Rs " + fee(p)); fees += fee(p); } System.out.println("Total fees: Rs " + fees); }}UPI meera@okbank -> fee Rs 0 Card *9012 -> fee Rs 50 Cash -> fee Rs 0 Total fees: Rs 50
What this code does
Paymentis sealed and permits exactly three records, so three cases cover every payment. Java 21 accepts both switches withoutdefault.- Two different switches act on the same data. The rules live in plain methods, and the compiler checks each one for missing cases.
Example 2 · The same idea with an enum (Java 14)
enum Slot { MORNING, AFTERNOON, EVENING }
public class EnumExhaustiveDemo { static String timing(Slot slot) { return switch (slot) { case MORNING -> "8:00 to 12:00"; case AFTERNOON -> "13:00 to 17:00"; case EVENING -> "18:00 to 21:00"; }; }
public static void main(String[] args) { for (Slot s : Slot.values()) { System.out.println(s + ": " + timing(s)); } }}MORNING: 8:00 to 12:00 AFTERNOON: 13:00 to 17:00 EVENING: 18:00 to 21:00
What this code does
- An enum has a fixed list of constants, so a switch expression listing all three is complete. This works on Java 17; there is no
default. - Sealed types bring the same safety to types that carry different fields per case, which an enum cannot do.
- Sealed interface + one case per permitted subtype → exhaustive, no
default. - Enum + one case per constant → exhaustive, no
default. - Records are final, so a record subtype needs exactly one unguarded case.
- Guarded cases do not count; each subtype needs an unguarded case.
With that knowledge, a switch with case Upi u, case Card c and case Cash c is complete. Java 21 accepts it with no default. The same idea already worked for enums: a switch expression over an enum that lists every constant needs no default (Java 14). Coverage also works through levels. If Card were itself sealed with Credit and Debit, then case Credit plus case Debit together would cover Card.
The compile error when a new subtype is added: a safety net
Business rules grow. One day the payments team adds NetBanking to the permits list. Every exhaustive switch over Payment now misses a case, and each one fails to compile with "the switch expression does not cover all possible input values".
Example 3 · Adding NetBanking: the compiler finds every switch
// Java 21sealed interface Payment permits Upi, Card, Cash, NetBanking { }
record Upi(String vpa, int amount) implements Payment { }
record Card(String last4, int amount) implements Payment { }
record Cash(int amount) implements Payment { }
record NetBanking(String bank, int amount) implements Payment { }
public class NewSubtypeErrorDemo { static int fee(Payment p) { return switch (p) { case Upi u -> 0; case Card c -> c.amount() * 2 / 100; case Cash c -> 0; }; }
public static void main(String[] args) { System.out.println(fee(new NetBanking("SBI", 5000))); }}NewSubtypeErrorDemo.java:14: error: the switch expression does not cover all possible input values
return switch (p) {
^
1 errorWhat this code does
NetBankingwas added topermits, butfeewas not updated. The switch is no longer complete, so the build fails right at that switch.- In a real project this error appears at every switch over
Payment: a free, exact list of the code that must decide what net banking costs.
Example 4 · Why default hides the new subtype
// Java 21sealed interface Payment permits Upi, Card, Cash, NetBanking { }
record Upi(String vpa, int amount) implements Payment { }
record Card(String last4, int amount) implements Payment { }
record Cash(int amount) implements Payment { }
record NetBanking(String bank, int amount) implements Payment { }
public class DefaultHidesBugDemo { static int fee(Payment p) { return switch (p) { case Card c -> c.amount() * 2 / 100; default -> 0; }; }
public static void main(String[] args) { System.out.println("Card fee: Rs " + fee(new Card("9012", 2500))); System.out.println("NetBanking fee: Rs " + fee(new NetBanking("SBI", 5000))); }}Card fee: Rs 50 NetBanking fee: Rs 0
What this code does
- This compiles, and net banking quietly gets a fee of 0, even if the bank charges for it. Nothing told the developer that a new payment type needed a decision.
- Over a sealed type, list every subtype instead of using
default. Then a new subtype is a compile error, not a silent wrong answer.
The compiler gives you a to-do list of every place that must decide what to do with net banking.
Compare that with a switch that has default. It still compiles, and the new type quietly falls into default. If that default returns a fee of 0, you will find out from an angry finance team, not from the compiler.
So for sealed types, leave out default on purpose. Let the compiler check your cases. If an old compiled class somehow meets a new subtype at run time, Java throws a MatchException instead of doing something wrong.
case null and case null, default (Java 21)
Before Java 21, a switch on a null value always threw a NullPointerException. That is still the default: a switch without a case null throws it, even if the switch is exhaustive.
- No
case null: a null value throwsNullPointerExceptionat theswitch. case null -> ...: null gets its own branch.case null, default -> ...: null and every unmatched value share one branch.- Put
case nullwhere it reads best, usually first or just beforedefault.
Example 5 · case null and case null, default
// Java 21sealed interface Payment permits Upi, Cash { }
record Upi(String vpa, int amount) implements Payment { }
record Cash(int amount) implements Payment { }
public class CaseNullDemo { static String old(Payment p) { return switch (p) { case Upi u -> "UPI"; case Cash c -> "Cash"; }; }
static String safe(Payment p) { return switch (p) { case null -> "not chosen yet"; case Upi u -> "UPI"; case Cash c -> "Cash"; }; }
static String city(String name) { return switch (name) { case "Mumbai", "Pune" -> "West zone"; case "Chennai" -> "South zone"; case null, default -> "Other zone"; }; }
public static void main(String[] args) { try { System.out.println(old(null)); } catch (NullPointerException e) { System.out.println("old(null) threw NullPointerException"); } System.out.println("safe(null): " + safe(null)); System.out.println("safe(cash): " + safe(new Cash(50))); System.out.println(city("Pune") + ", " + city(null) + ", " + city("Jaipur")); }}old(null) threw NullPointerException safe(null): not chosen yet safe(cash): Cash West zone, Other zone, Other zone
What this code does
oldis exhaustive but has nocase null, so anullpayment still throwsNullPointerExceptionat the switch.case null ->gives null its own branch. Incity,case null, defaultsends bothnulland unknown cities to one branch; this works in a plainStringswitch too.
Java 21 adds case null ->, so the switch can handle a missing value itself, for example a customer who has not chosen a payment method yet. You can also join it with the default: case null, default -> ... sends both null and "anything else" to the same branch. case null works in any switch on a reference type, including old-style String and enum switches. case null does not count toward exhaustiveness; it only adds the null value to the cases you already have.
Interview point: why sealed types and switch work well together
A sealed interface with record subtypes models data that comes in a fixed set of shapes: a payment is UPI or card or cash, each with its own fields. A pattern switch is the natural way to act on such data: one case per shape.
Together they give three guarantees. The compiler knows every shape. It checks that every switch handles every shape. And when a shape is added, it points at every switch that must change. Rules about the data can live outside the classes, in one readable switch, without losing safety.
This style is sometimes called data-oriented programming: plain data types plus functions that switch over them. It suits reports, fees and parsers. Classic polymorphism, with a method on each class, still suits behaviour that each class should own.
Next step
Check your understanding
12 quick questions