Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Switch Pattern Matching

Learn how pattern matching for switch works in Java: type patterns, guarded patterns, null handling, and when the feature is a good fit.

~5 min readJava
#Java 17#Pattern Matching#Switch Expressions#Type Patterns
Java code snippet showing a switch expression with type patterns and guarded cases

Pattern matching for switch, introduced as a preview in Java 17 and finalized in Java 21, changes how developers write type-based branching. Instead of a chain of if statements combined with instanceof checks and manual casts, you can select a branch based on a pattern that also binds variables. This article explains the syntax, practical usage, and important limitations.

The Core Syntax and a Minimal Example

A switch statement or expression can now use type patterns as case labels. Consider a method that processes an object that could be a String, an Integer, or a null. Without pattern matching, you would write an if chain with instanceof and casts:

java
Object obj = ...; if (obj instanceof String s) { System.out.println(s.length()); } else if (obj instanceof Integer i) { System.out.println(i + 1); } else { System.out.println("Unknown type"); }

With pattern matching for switch, the same logic becomes a switch expression:

java
Object obj = ...; String result = switch (obj) { case String s -> "Length: " + s.length(); case Integer i -> "Value: " + (i + 1); default -> "Unknown type"; };

Each case checks whether the selector expression matches the pattern. If it matches, the bound variable (s or i) is already cast and available. There is no separate cast step. This reduces boilerplate and keeps related branches close together.

Why This Improves Readability and Maintainability

The if-instanceof chain works, but it becomes harder to read as the number of types grows. Each branch must repeat the instanceof check, the cast, and the variable declaration. With pattern matching, the pattern itself conveys the type and binding. This is especially visible when you handle a sealed hierarchy, where the compiler can often verify that you have covered all possible subtypes.

Consider a sealed interface Shape with records Circle and Rectangle. Using pattern matching for switch, you can write:

java
sealed interface Shape permits Circle, Rectangle {} record Circle(double radius) implements Shape {} record Rectangle(double width, double height) implements Shape {} double area(Shape shape) { return switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.width() * r.height(); }; }

Because Shape is sealed, the compiler knows there are only two possible subtypes, and you do not need a default branch. If you later add a new permitted subtype, the switch will no longer compile until you handle it. That kind of compile-time safety is impossible with an if chain. For an open interface, a default branch remains necessary.

Guarded Patterns and Fine-Grained Conditions

A type pattern alone matches all non-null values of that type. If you need additional conditions, you can use a guarded pattern with the when keyword. Example:

java
String classify(Integer i) { return switch (i) { case Integer n when n > 0 -> "positive"; case Integer n when n < 0 -> "negative"; case Integer n -> "zero"; }; }

The guard n > 0 is evaluated only after the pattern Integer n matches. If the guard is false, the switch continues to the next case. Guards are useful when you want to combine type matching with a specific condition without falling back to nested if statements. Note that the guard should be a pure condition; side effects in guards make the control flow harder to reason about.

Handling Null Explicitly

In traditional switch statements and expressions, passing null to the selector throws a NullPointerException unless you check for null beforehand. With pattern matching for switch, you can handle null directly as a case:

java
String describe(Object obj) { return switch (obj) { case null -> "null"; case String s -> "String: " + s; case Integer i -> "Integer: " + i; default -> "Other"; }; }

Because type patterns do not match null, a null selector is handled only by case null; without it, the switch throws a NullPointerException. Putting the null case first is conventional and makes the behavior explicit.

Runtime Behavior and Performance Considerations

The compiler translates pattern matching for switch into bytecode that behaves similarly to an if-instanceof chain, but there can be subtle differences in how the cases are ordered and optimized. In general, the runtime cost is comparable to a series of type checks. You should not avoid pattern matching for performance reasons without first profiling. For most application code, the readability and safety benefits outweigh any micro-optimizations you might achieve with manual casts.

Like a chain of else if, a pattern switch normally evaluates type tests in order until one matches. This is usually not a problem when there are only a handful of types. If you have many types on a hot path, consider a different dispatch structure, such as a Map of functions or polymorphic dispatch. For typical domain models, the switch is clear and efficient enough.

Common Mistakes and How to Avoid Them

One common mistake is to write a pattern that is impossible to match, leading to a compile-time error. For example:

java
switch (obj) { case String s -> System.out.println(s); case CharSequence cs -> System.out.println(cs); // Compile error: CharSequence is a supertype of String }

The compiler rejects a pattern that is already covered by an earlier, more specific pattern. Similarly, you cannot have two identical type patterns. This is a feature: it forces you to order cases from most specific to least specific, preventing accidental shadowing.

Another mistake is to use a guarded pattern that is too broad, such as case String s when true. That is redundant. Also, be wary of guards that throw exceptions. If a guard throws, the exception propagates and the switch does not fall through to the next case. For maintainability, keep guards side-effect-free and simple.

Compatibility and Version Requirements

Pattern matching for switch is not available in earlier Java versions. In Java 17 through Java 20, it was a preview feature; you had to enable it with --enable-preview. In Java 21, it became a final feature, so no preview flag is required. If you are using an older version, you cannot directly use this syntax. You can either upgrade the Java runtime or stick with the traditional instanceof chain.

Also check the deployment environment. Preview bytecode is tied to the JDK release used to compile it and requires the same release with preview features enabled; code compiled with Java 21 generally requires a Java 21 or later runtime. The exact behavior of case null and type patterns depends on the Java version, so always test on the target runtime. For code that must run on Java 11 or 8, this feature is simply unavailable, so plan accordingly.

When Pattern Matching for Switch Is Not the Right Choice

Pattern matching for switch is excellent for type-based dispatch, but it is not a universal replacement for all switch usage. If your switch is only testing integer constants or enums, the traditional case with constants is still appropriate. Pattern matching adds no value there. Also, if you need to check multiple conditions on the same value that do not reduce to a single type pattern, a series of if statements might be clearer.

Another scenario is when you want to match a pattern that depends on runtime data that is not the selector itself. For example, matching a Map entry based on a key type is not directly supported. You would need to extract the values or create a record to match against. In general, pattern matching works best with sealed hierarchies and records, or when you are handling a loosely typed object such as a JSON value where each type has distinct semantics.

A maintainability tradeoff: Adding a new case to a pattern-matching switch is straightforward, but removing or reordering cases can cause subtle compiler errors if you forget that a supertype pattern covers a subtype. Rely on the compiler to warn you about dominance, and use sealed hierarchies to get exhaustiveness checks. That yields a switch that the compiler keeps honest as your domain model evolves.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.