☕ Java

Java Pattern Matching for switch (Java 21): Type Patterns, when Guards and case null

Java 21 pattern matching for switch: type patterns, when guards, case null, dominance rules and sealed exhaustiveness, with examples and common compile errors.

Why switch Needed Pattern Matching: Replacing instanceof Chains

Before Java 21, a switch could only compare its selector against constants: int and char literals, enum constants, and (since Java 7) String literals. It could never test a type. Code that had to branch on the runtime type of a value fell back to a chain of if/else-if statements with instanceof checks. Pattern matching for instanceof (Java 16) removed the explicit cast, but the chain was still a series of independent boolean tests. The compiler could not check that every relevant type was handled, and long chains are harder to scan than a flat list of case labels. Pattern matching for switch (JEP 441, final in Java 21) lets a case label be a type pattern such as case Integer i. The switch tests the selector's runtime type and binds a correctly typed variable in one step. The result is a single list of alternatives, and when the selector is a sealed type the compiler can verify that every subtype is covered.
Java
// Before Java 21: type dispatch via chained instanceof / else-if
String describeOld(Object obj) {
    if (obj instanceof Integer i) {
        return "Integer: " + i;
    } else if (obj instanceof Long l) {
        return "Long: " + l;
    } else if (obj instanceof String s) {
        return "String of length " + s.length();
    } else if (obj instanceof Double d) {
        return "Double: " + d;
    } else {
        return "Unknown: " + obj;
    }
}
// Nothing checks that every relevant type was considered.

// Java 21: pattern matching for switch
String describe(Object obj) {
    return switch (obj) {
        case Integer i -> "Integer: " + i;
        case Long l    -> "Long: " + l;
        case String s  -> "String of length " + s.length();
        case Double d  -> "Double: " + d;
        default        -> "Unknown: " + obj;
    };
}

Pattern Matching for switch Version History (Java 16 to 22)

The feature went through four preview rounds before it became final, so older blog posts and Stack Overflow answers may show syntax that no longer compiles. The biggest change was in Java 19, when guards moved from the && operator to the when keyword. Preview features need the --enable-preview flag, which is not required on Java 21 and later for this feature.
Text
Java 16  Pattern matching for instanceof            JEP 394  (final)
Java 17  Pattern matching for switch                JEP 406  (first preview)
Java 18  Pattern matching for switch                JEP 420  (second preview)
Java 19  Pattern matching for switch                JEP 427  (third preview, guards use "when")
Java 20  Pattern matching for switch                JEP 433  (fourth preview)
Java 21  Pattern matching for switch                JEP 441  (final)
Java 21  Record patterns                            JEP 440  (final)
Java 22  Unnamed patterns and variables (_)         JEP 456  (final)

// Old preview syntax (Java 17-18), no longer valid:
//   case String s && s.length() > 5 -> ...
// Current syntax (Java 19 preview, final in 21):
//   case String s when s.length() > 5 -> ...

Type Pattern Syntax and Pattern Variable Scope

A type pattern is a type followed by a variable name. If the selector's runtime type matches, the variable is bound to the selector already cast to that type, with no explicit cast needed. The variable is in scope only inside its own case arm. Arrow arms (->) are the cleanest form because they never fall through. A switch expression with patterns must be exhaustive, so Object selectors need a default arm (or an unconditional pattern such as case Object o). A null selector throws NullPointerException unless the switch has a case null label.
Java
static String format(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %.2f", d);
        case String s  -> String.format("String %s", s);
        default        -> obj.toString();
    };
}

// Pattern switch used as a statement (no value produced)
static void log(Object obj) {
    switch (obj) {
        case String s  -> System.out.println("text: " + s);
        case Integer i -> System.out.println("number: " + i);
        default        -> System.out.println("other: " + obj);
    }
}
// The variable s exists only inside its own arm.

Mixing Constant Labels and Type Patterns

Constant labels and pattern labels can appear in the same switch, and the first matching label wins. One restriction matters here: constant labels are only legal when the selector type supports them (int-like types and their wrappers, String, or an enum). A switch on Object cannot contain case 0. To special-case values on an Object selector, use a guarded pattern such as case Integer i when i == 0. When constants and patterns share a switch, put the constants first, because a pattern that already matches that type would dominate and make a later constant unreachable.
Java
// Integer selector: constants first, then patterns
String classify(Integer n) {
    return switch (n) {
        case 0 -> "zero";
        case 1 -> "one";
        case Integer i when i < 0 -> "negative: " + i;
        case Integer i -> "positive: " + i;      // unconditional, so no default needed
    };
}

// String selector: constants first, then patterns
String route(String cmd) {
    return switch (cmd) {
        case "start" -> "Starting";
        case "stop"  -> "Stopping";
        case String s when s.startsWith("run ") -> "Running " + s.substring(4);
        case String s -> "Unknown command: " + s;
    };
}

// Object selector: constant labels are NOT allowed
// String bad(Object obj) {
//     return switch (obj) {
//         case 0 -> "zero";          // COMPILE ERROR: int constant on an Object selector
//         default -> "other";
//     };
// }

// Fix: use a guarded type pattern instead
String good(Object obj) {
    return switch (obj) {
        case Integer i when i == 0 -> "zero";
        case Integer i -> "int: " + i;
        default -> "other";
    };
}

// Constant placed AFTER a dominating pattern is an error
// switch (n) {
//     case Integer i -> "any int";
//     case 0 -> "zero";              // COMPILE ERROR: dominated by the pattern above
// }

Dominance Rules: Why Case Order Matters

Case labels are checked top to bottom and the first match wins. To stop you from writing dead code, the compiler rejects any label that an earlier label already covers completely. This is a compile error, not a warning. Placing case Object o before case String s fails because Object matches everything String could match. Order type patterns from most specific to least specific. The same applies to guards. An unguarded pattern dominates any later pattern on the same or a narrower type, but a guarded pattern does not, because its guard may be false. Also note that an unconditional pattern (one that matches every possible selector value, such as case Object o on an Object selector) cannot be combined with a default label in the same switch. Use one or the other.
Java
Object value = "test";

// Wrong: general pattern first
// String r = switch (value) {
//     case Object o -> "Any object: " + o;
//     case String s -> "String: " + s;
//     // COMPILE ERROR: "this case label is dominated by a preceding case label"
// };

// Correct: specific first, general last (exhaustive, so no default)
String r = switch (value) {
    case String s -> "String: " + s;
    case Object o -> "Any object: " + o;
};

// Unconditional pattern + default is also an error
// String r2 = switch (value) {
//     case Object o -> "any";
//     default -> "x";
//     // COMPILE ERROR: "switch has both an unconditional pattern and a default label"
// };

// Guards: guarded first is fine, unguarded first is dominance
String size(Object obj) {
    return switch (obj) {
        case String s when s.length() > 10 -> "long string";
        case String s -> "short string";        // legal: the guarded label above does not dominate it
        default -> "not a string";
    };
}

Guarded Patterns with when

A guard adds a boolean condition to a type pattern: case Type t when condition. The arm matches only if the type matches and the condition is true. If the type matches but the guard is false, the switch simply moves on to the next label as if the pattern had not matched. The guard can use the pattern variable and any other variables in scope, and it can combine conditions with && and ||. Prefer guards over nested if statements inside an arm, because they keep the dispatch logic flat and let later arms handle the leftover cases.
Java
String bucket(Object obj) {
    return switch (obj) {
        case Integer i when i > 100 -> "large int";
        case Integer i when i > 0   -> "small positive int";
        case Integer i              -> "zero or negative int";
        case String s when s.isBlank() -> "blank string";
        case String s               -> "string: " + s;
        default                     -> "other";
    };
}

// bucket(150)  -> "large int"
// bucket(5)    -> "small positive int"
// bucket(-3)   -> "zero or negative int"
// bucket("  ") -> "blank string"
// bucket(2.5)  -> "other"

Handling null with case null and case null, default

A traditional switch throws NullPointerException as soon as the selector is null, before any label is considered. Pattern matching for switch keeps that default for backward compatibility. To handle null inside the switch, add a case null label. You can also write case null, default to give null and every unmatched value the same treatment. Combining case null with a type pattern such as case null, String s is not allowed in Java 21. Without case null, a null selector still throws NullPointerException, even if the switch has a default arm.
Java
String describe(Object obj) {
    return switch (obj) {
        case null      -> "Got null";           // explicit opt-in, no pre-check needed
        case Integer i -> "Integer: " + i;
        default        -> "Something else: " + obj;
    };
}

String describeCombined(Object obj) {
    return switch (obj) {
        case Integer i -> "Integer: " + i;
        case null, default -> "Null or unrecognized: " + obj;
    };
}

// Without case null:
// describe2(null) throws NullPointerException even though default exists

Exhaustiveness and Sealed Types

Switch expressions must be exhaustive, and so must pattern switch statements and any switch that uses case null. If the selector is a sealed type (or an enum) and every permitted subtype is covered by an unconditional case, you can omit default. A guarded pattern does not count as covering its type, because the guard might be false at runtime. A switch that only uses guarded cases for a subtype therefore needs an unconditional fallback for that subtype, or a default. The practical benefit is maintenance. If you later add a new permitted subtype, every switch without a default fails to compile until you handle it, so the compiler finds all the places that need updating. If a subtype is added without recompiling a switch, the switch throws MatchException at runtime instead of silently doing nothing.
Java
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}

// Guard alone does not make Circle "covered"
// double areaBad(Shape shape) {
//     return switch (shape) {
//         case Circle c when c.radius() > 0 -> Math.PI * c.radius() * c.radius();
//         case Square s -> s.side() * s.side();
//         // COMPILE ERROR: "the switch expression does not cover all possible input values"
//     };
// }

// Fix: add an unconditional fallback for Circle
double areaFixed(Shape shape) {
    return switch (shape) {
        case Circle c when c.radius() > 0 -> Math.PI * c.radius() * c.radius();
        case Circle c -> 0.0;
        case Square s -> s.side() * s.side();
        // exhaustive: no default needed
    };
}

Record Patterns Inside switch

Type patterns combine with record patterns (JEP 440, final in Java 21) to deconstruct a record directly in the case label. The components are bound to variables, and guards can use them. This keeps data-oriented code short: the type check, the field extraction and the condition all happen in one label.
Java
record Point(int x, int y) {}

String where(Object obj) {
    return switch (obj) {
        case Point(int x, int y) when x == 0 && y == 0 -> "origin";
        case Point(int x, int y) when x == y           -> "diagonal at " + x;
        case Point(int x, int y)                       -> "point " + x + "," + y;
        default                                        -> "not a point";
    };
}

Multiple Patterns per Label and Fall-Through Restrictions

With constants you can share one arm using commas (case 1, 2, 3). With patterns that declare variables this is restricted. In Java 21 a single label cannot list several patterns that each bind a variable, because the arm would not know which variable exists. Either write separate arms or, from Java 22, use unnamed patterns (_) when you do not need the value. The old colon-style switch can also fall through, but it is a compile error to fall through into a pattern label that declares a variable. Use arrow arms to avoid the problem.
Java
// Java 21: ERROR, several patterns in one label declaring variables
// case Integer i, Long l -> "number";

// Works in Java 21: separate arms
String kind(Object obj) {
    return switch (obj) {
        case Integer i -> "number " + i;
        case Long l    -> "number " + l;
        default        -> "other";
    };
}

// Java 22+: unnamed patterns allow a shared arm
// String kind22(Object obj) {
//     return switch (obj) {
//         case Integer _, Long _ -> "some number";
//         default -> "other";
//     };
// }

// Colon-style fall-through into a pattern label is an error
// switch (obj) {
//     case Integer i:
//         System.out.println(i);
//     case String s:          // COMPILE ERROR: falls through to a pattern that declares s
//         System.out.println(s);
// }

Common Compile Errors and How to Fix Them

Most problems with pattern matching for switch fall into a few categories. The compiler messages are specific, so the fix is usually a reordering or one extra arm.
Text
Error                                                    Cause                                      Fix
-----------------------------------------------------------------------------------------------------------------------
"this case label is dominated by a preceding case label" An earlier label already covers this one   Put specific patterns first
"the switch expression does not cover all possible       Not exhaustive (missing subtype, or only   Add the missing case, an
 input values"                                           guarded cases for a subtype)               unconditional fallback, or default
"switch has both an unconditional pattern and a          case Object o (or similar) plus default    Remove default or the pattern
 default label"
Constant label rejected on an Object selector            case 0 / case "x" on a non-constant type   Use case Integer i when i == 0
Pattern label after a fall-through                       Colon-style arm falls into a pattern       Use arrow arms or add break
NullPointerException at runtime                          Selector is null and there is no case null Add case null or check beforehand
MatchException at runtime                                Sealed hierarchy changed after compiling   Recompile every switch over that type

Pattern Matching for switch FAQ

Short answers to the questions developers search for most often.
Text
Q: Which Java version has pattern matching for switch?
A: Final in Java 21 (JEP 441). It was a preview feature in Java 17 to 20.

Q: Is a pattern switch faster than an instanceof chain?
A: Do not choose it for speed. The main benefits are readability and compiler-checked exhaustiveness.

Q: Can I use primitive types like int in a type pattern?
A: Not in Java 21. Type patterns use reference types, so use Integer, not int, on an Object selector.

Q: Does a default arm still run for null?
A: No. A null selector throws NullPointerException unless the switch has case null.

Q: Do I need default on a sealed hierarchy?
A: No, if every permitted subtype has an unconditional case. Omitting it lets the compiler flag new subtypes.

Q: When should I keep if/else instead?
A: For one or two type checks, or when each branch needs unrelated conditions, a plain if can be simpler.

Related Topics in Java 9 to 21 Features

Module System (JPMS)
The Java Platform Module System (JPMS), introduced in Java 9 under Project Jigsaw, adds a module as a new, higher-level unit of code organization above the package, allowing a JAR-like artifact to explicitly declare which packages it exports for use by other modules, which modules it depends on, and which packages it keeps entirely internal and inaccessible from outside — closing a long-standing gap in the classpath model where every public class in every JAR on the classpath was accessible to every other JAR, regardless of whether that access was intended. JPMS was also the mechanism used to decompose the JDK itself, which had grown into one monolithic rt.jar, into roughly 90 separate modules, enabling smaller custom runtime images and explicit internal-API encapsulation (notably restricting access to sun.* and other internal packages that many libraries had relied on despite warnings). This entry covers the classpath problems JPMS solves, module-info.java syntax and the requires/exports/opens directives, the distinction between the classpath and module path including automatic and unnamed modules, and jlink custom runtime images.
JShell
JShell, introduced in Java 9, is an interactive Read-Eval-Print Loop (REPL) bundled directly with the JDK, allowing Java statements, expressions, method, class, and variable declarations to be entered and evaluated one at a time at an interactive prompt, with immediate feedback — without requiring a class wrapper, a main method, explicit compilation, or a build tool, all of which Java had always required for even the smallest snippet of executable code before Java 9. This solved a long-standing friction point for learning, quick experimentation, and API exploration, where languages like Python or Ruby offered an immediate interactive prompt but Java required the full edit-compile-run cycle even to test a single line. This entry covers what problem JShell solves and how it differs from a script, core REPL usage including implicit variable creation and forward references, snippet management commands, and how to feed JShell external classes and files.
Collection Factory Methods
Collection factory methods — List.of(...), Set.of(...), and Map.of(...)/Map.ofEntries(...) — introduced in Java 9, provide a concise, standard way to create small, fixed-content, genuinely immutable collections in a single expression, replacing the previously common but verbose combination of Arrays.asList(...), Collections.unmodifiableList(...), and manual add() calls, none of which produced a collection that was both concise to write and fully immutable. This entry covers exactly what problem these factories solve compared to the older idioms, the specific immutability and null-rejection guarantees they provide (which are stricter than Collections.unmodifiableXxx), their behavior around duplicate keys/elements, and important caveats around mutability expectations and performance for very small collections.
Private Interface Methods
Private interface methods, introduced in Java 9, allow an interface to declare methods marked private — with a full method body — that are accessible only from within that same interface (from its default methods, its other private methods, and its private static methods), but completely invisible to implementing classes and to any code outside the interface. They close a code-duplication gap left after Java 8's default methods: when an interface has multiple default methods that share common logic, that shared logic previously either had to be duplicated in each default method or exposed as a public default method purely to enable reuse, polluting the interface's actual API surface with a method meant only for internal reuse. This entry covers the specific problem they solve, the distinction between private instance and private static interface methods, the rules governing what they can call and be called from, and how they interact with the broader default-method design Java established in version 8.