Pattern matching for switch goes final

Java 21 Course · lesson 5 of 15 · 4 min read

After three previews, switch on types became a real language feature in 21.

Open this lesson in the learning hub

Key points

  • A switch can now match on type, binding a typed variable in the same step.
  • Combined with sealed types the compiler proves the switch is exhaustive - no default needed.
  • Add a permitted subtype later and every switch that misses it becomes a compile error, not a runtime surprise.
  • when clauses add a guard: case Integer i when i > 100 -> ....
  • null no longer throws automatically - you can write case null explicitly.

Example

public class Main {
    sealed interface Shape permits Circle, Square, Rect { }
    record Circle(double r) implements Shape { }
    record Square(double side) implements Shape { }
    record Rect(double w, double h) implements Shape { }

    static String describe(Shape s) {
        // No default branch: the compiler knows the list is complete
        return switch (s) {
            case Circle c when c.r() > 10 -> "big circle r=" + c.r();
            case Circle c                 -> "circle r=" + c.r();
            case Square q                 -> "square side=" + q.side();
            case Rect r                   -> "rect " + r.w() + "x" + r.h();
        };
    }

    static String nullSafe(Object o) {
        return switch (o) {
            case null      -> "it was null";
            case String s  -> "string of length " + s.length();
            case Integer i -> "int " + i;
            default        -> "something else";
        };
    }

    public static void main(String[] args) {
        System.out.println(describe(new Circle(12)));
        System.out.println(describe(new Circle(2)));
        System.out.println(describe(new Rect(3, 4)));
        System.out.println(nullSafe(null));
        System.out.println(nullSafe("hello"));
    }
}

Sealed types plus pattern switch move "did I handle every case?" from code review to the compiler.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 21 Course course, and every lesson in it is listed on the Java 21 Course contents page.