00:00

Pattern Matching for switch in Java 21

Last updated: · Standard (Java 21)

Pattern matching for switch is a standard feature in Java 21 (JEP 441), after four previews starting in Java 17. A switch can now test the type of any object, refine matches with when guards, handle null, and check that every case is covered.

This tutorial explains the final syntax, the rules the compiler enforces, and the small additions made in Java 21.

1. Why Is It Needed?

Business rules often depend on the kind of object you have: different events, payments or messages. Long if-else chains with instanceof are hard to read and the compiler cannot tell you when a case is missing. A pattern switch is shorter, returns a value, and becomes exhaustive with sealed types.

2. Syntax

Syntax.java
return switch (event) {
    case null -> "no event";
    case Login l when !l.twoFactor() -> "medium risk";   // guard
    case Login l -> "low risk";
    case Purchase p -> "check amount " + p.amount();
    case Logout lo -> "none";
};
  • Labels are checked from top to bottom; a guard with when adds a condition.
  • case null handles a null selector; without it, null throws NullPointerException.
  • A label that can never be reached because an earlier one always matches first is a dominance error.

3. Practical Examples

Example 1: Guards, null and sealed types

GuardsAndNull.java
public class GuardsAndNull {
    sealed interface Event permits Login, Purchase, Logout { }
    record Login(String user, boolean twoFactor) implements Event { }
    record Purchase(String user, double amount) implements Event { }
    record Logout(String user) implements Event { }

    static String risk(Event e) {
        return switch (e) {
            case null -> "no event";
            case Login l when !l.twoFactor() -> "MEDIUM: " + l.user() + " logged in without 2FA";
            case Login l -> "LOW: " + l.user() + " logged in";
            case Purchase p when p.amount() > 50_000 -> "HIGH: " + p.user() + " spent " + p.amount();
            case Purchase p -> "LOW: purchase by " + p.user();
            case Logout lo -> "NONE: " + lo.user() + " logged out";
        };
    }

    public static void main(String[] args) {
        Event[] events = { new Login("asha", true), new Login("ravi", false),
                new Purchase("meera", 75_000), new Purchase("john", 900), new Logout("asha"), null };
        for (Event e : events) {
            System.out.println(risk(e));
        }
    }
}
Output
LOW: asha logged in
MEDIUM: ravi logged in without 2FA
HIGH: meera spent 75000.0
LOW: purchase by john
NONE: asha logged out
no event

Example 2: Qualified enum constants

New in Java 21, enum constants can be written with their type name, so one switch can cover constants from two enums that implement the same sealed interface.

QualifiedEnums.java
public class QualifiedEnums {
    sealed interface Command permits Move, Action { }
    enum Move implements Command { UP, DOWN }
    enum Action implements Command { JUMP, FIRE }

    // Java 21: qualified enum constants as case labels, exhaustive over the sealed interface
    static String handle(Command c) {
        return switch (c) {
            case Move.UP -> "moving up";
            case Move.DOWN -> "moving down";
            case Action.JUMP -> "jumping";
            case Action.FIRE -> "firing";
        };
    }

    public static void main(String[] args) {
        for (Command c : new Command[] { Move.UP, Action.FIRE, Move.DOWN, Action.JUMP }) {
            System.out.println(c + " -> " + handle(c));
        }
    }
}
Output
UP -> moving up
FIRE -> firing
DOWN -> moving down
JUMP -> jumping

Example 3: A dominated label

Dominance.java
public class Dominance {
    static String kind(Object o) {
        return switch (o) {
            case CharSequence cs -> "char sequence";
            case String s -> "string";             // never reachable: String is a CharSequence
            default -> "other";
        };
    }

    public static void main(String[] args) {
        System.out.println(kind("x"));
    }
}
Compiler output
Dominance.java:5: error: this case label is dominated by a preceding case label
            case String s -> "string";             // never reachable: String is a CharSequence
                 ^
1 error

4. How the Compiler Checks a Pattern Switch

Compiler checks for a pattern switch The compiler checks label order for dominance, checks that the cases are exhaustive for the selector type, and then generates efficient type dispatch code. case labels patterns + guards dominance check no unreachable label exhaustiveness all subtypes covered compiled switch type dispatch
Figure 1: Mistakes such as unreachable or missing cases are reported at compile time.

5. Important Points and Best Practices

  • Prefer sealed types and no default, so adding a subtype produces compile errors everywhere it must be handled.
  • Put guarded labels before the unguarded label of the same type.
  • Keep guards simple and free of side effects.
  • If no case null exists, the switch still throws NullPointerException for null.
  • Java 22 added unnamed patterns (_) for components you want to ignore.

6. Summary

  • Pattern matching for switch is final in Java 21 (JEP 441).
  • Labels can be type patterns, record patterns, case null and qualified enum constants.
  • when guards refine a pattern.
  • The compiler checks dominance and exhaustiveness.

Related Tutorials

7. References