Video in progress

Middle ☕ Core Java

How does pattern matching in Java 21 (instanceof and switch) simplify code?

The instanceof check and the cast happen in one step, and switch can work by type, unpack a record (a record pattern) and take an extra condition (when). Casts and long if-else chains go away.

📖 Answer

The old style:

if (shape instanceof Circle) {
    Circle c = (Circle) shape;
    return Math.PI * c.r() * c.r();
}

The instanceof pattern (Java 16):

if (shape instanceof Circle c) {
    return Math.PI * c.r() * c.r();
}

Switch patterns and record patterns (Java 21):

double area(Shape s) {
    return switch (s) {
        case Circle(double r)                -> Math.PI * r * r;
        case Rect(double w, double h) when w == h -> w * w;   // a square
        case Rect(double w, double h)        -> w * h;
    };
}

Subtle points:

  • order matters: if a more general case comes before a more specific one, the compiler gives an error ("dominated");
  • null: an ordinary switch throws an NPE on null; you can catch it with a separate case null ->;
  • with a sealed hierarchy, default isn't required and coverage is checked.

When not to use it: a switch on type in your own classes is often used in place of polymorphism. If every type should have its own behavior, it's more correct to put the method in the class itself. Pattern matching is strong when you work with data (records, DTOs, events).