00:00

Pattern Matching for switch in Java 17 (Preview)

Last updated: · Preview in Java 17

Pattern matching for switch lets a case label test the type of a value and bind it to a variable in one step. Java 17 shipped the first preview (JEP 406). After three more previews it became a standard feature in Java 21 (JEP 441).

This tutorial explains the Java 17 preview, how to enable it, and what changed before the feature was finalised.

1. Why Is This Feature Needed?

Code that handles several types usually becomes a chain of if (x instanceof A a) ... else if (x instanceof B b) .... A switch expresses the same idea more clearly, returns a value, and, for sealed types, lets the compiler confirm that every case is handled. Before this feature, switch only worked with numbers, strings and enums.

2. Syntax and Preview Flags

Syntax.java
return switch (value) {
    case null      -> "null value";           // explicit null handling
    case Integer i -> "integer " + i;          // type pattern
    case String s  -> "text " + s;
    default        -> "something else";
};

Because it is a preview feature in Java 17, it must be enabled when compiling and running:

Commands
javac --release 17 --enable-preview TypePatternSwitch.java
java --enable-preview TypePatternSwitch

Version note: in the Java 17 preview, extra conditions were written as guarded patterns with &&, for example case String s && s.isEmpty(). Java 19 replaced this with when, which is the form used in Java 21 and later.

3. Practical Examples

How these examples were verified: a JDK 17 was not available in our test environment, so the examples were compiled and run on JDK 21, where the feature is final. They avoid guards and use only syntax that is valid in both the Java 17 preview and Java 21.

Example 1: Type patterns and case null

TypePatternSwitch.java
// Preview in Java 17 (JEP 406): javac --release 17 --enable-preview, java --enable-preview
// Final since Java 21 (JEP 441)
public class TypePatternSwitch {
    static String format(Object value) {
        return switch (value) {
            case null -> "null value";
            case Integer i -> "integer " + i;
            case Long l -> "long " + l + "L";
            case Double d -> String.format("double %.2f", d);
            case String s -> "text \"" + s + "\" (" + s.length() + " chars)";
            default -> "unsupported " + value.getClass().getSimpleName();
        };
    }

    public static void main(String[] args) {
        Object[] values = { 42, 9_000_000_000L, 3.14159, "invoice", 'x', null };
        for (Object v : values) {
            System.out.println(format(v));
        }
    }
}
Output
integer 42
long 9000000000L
double 3.14
text "invoice" (7 chars)
unsupported Character
null value

Example 2: Exhaustive switch over a sealed interface

The switch has no default. The compiler knows Notification is sealed and that all three permitted records are covered.

SealedExhaustive.java
// Preview in Java 17 (JEP 406); final since Java 21 (JEP 441)
public class SealedExhaustive {
    sealed interface Notification permits Email, Sms, Push { }
    record Email(String to, String subject) implements Notification { }
    record Sms(String phone) implements Notification { }
    record Push(String device) implements Notification { }

    // All permitted subtypes are covered, so no default branch is needed
    static String channel(Notification n) {
        return switch (n) {
            case Email e -> "email to " + e.to() + " [" + e.subject() + "]";
            case Sms s -> "sms to " + s.phone();
            case Push p -> "push to " + p.device();
        };
    }

    public static void main(String[] args) {
        Notification[] outbox = { new Email("asha@mail.com", "Invoice"), new Sms("98450 11111"), new Push("pixel-8") };
        for (Notification n : outbox) {
            System.out.println(channel(n));
        }
    }
}
Output
email to asha@mail.com [Invoice]
sms to 98450 11111
push to pixel-8

4. Path from Preview to Final

VersionJEPStatus
Java 17JEP 406first preview: type patterns, case null, guarded patterns with &&
Java 18JEP 420second preview
Java 19JEP 427third preview: when guards replace &&
Java 20JEP 433fourth preview
Java 21JEP 441final, no flags needed
How a pattern switch chooses a branch The selector value is tested against each case label from top to bottom; the first matching pattern binds the variable and its branch runs. selector Object value case null? handled first type patterns checked top to bottom first match binds variable, runs
Figure 1: More specific patterns must come before more general ones, or the compiler reports a dominance error.

5. Important Points and Best Practices

  • Do not use preview features in production code on Java 17; their syntax can change, and it did.
  • Without case null, a pattern switch still throws NullPointerException for a null selector.
  • Order matters: case CharSequence cs before case String s is a compile error because the first label dominates the second.
  • For production use, prefer Java 21 or later, where the feature is final.

6. Summary

  • Java 17 previewed pattern matching for switch (JEP 406).
  • Case labels can test types, bind variables and handle null.
  • Preview features require --enable-preview at compile time and run time.
  • The feature became final in Java 21 (JEP 441), with when guards.

Related Tutorials

7. References