Skip to lesson
MentorNxt home

Java Programming

Pattern Matching & Newer Language Features

Exhaustive switch and case null

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

SealedSwitchDemo.javaJava
// 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);    }}
Output
UPI meera@okbank -> fee Rs 0
Card *9012 -> fee Rs 50
Cash -> fee Rs 0
Total fees: Rs 50

What this code does

  • Payment is sealed and permits exactly three records, so three cases cover every payment. Java 21 accepts both switches without default.
  • 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)

EnumExhaustiveDemo.javaJava
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));        }    }}
Output
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".

Left: Circle, Rectangle and Triangle all have a case, so the switch compiles with no default. Right: the Triangle case is missing, so the Java compiler stops with a compile error because the switch is not exhaustive.

Example 3 · Adding NetBanking: the compiler finds every switch

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

What this code does

  • NetBanking was added to permits, but fee was 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

DefaultHidesBugDemo.javaJava
// 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)));    }}
Output
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.

  1. No case null: a null value throws NullPointerException at the switch.
  2. case null -> ...: null gets its own branch.
  3. case null, default -> ...: null and every unmatched value share one branch.
  4. Put case null where it reads best, usually first or just before default.

Example 5 · case null and case null, default

CaseNullDemo.javaJava
// 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"));    }}
Output
old(null) threw NullPointerException
safe(null): not chosen yet
safe(cash): Cash
West zone, Other zone, Other zone

What this code does

  • old is exhaustive but has no case null, so a null payment still throws NullPointerException at the switch.
  • case null -> gives null its own branch. In city, case null, default sends both null and unknown cities to one branch; this works in a plain String switch 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