Skip to content
AgileLogics
5 min read

Pattern Matching

Prerequisites: Sealed classes

Pattern matching for instanceof (Java 16+) combines a type check and a cast into one step:

Object obj = "hello";

if (obj instanceof String s) {
    System.out.println(s.length()); // s is already a String here
}

Combined with a sealed type, a switch expression can match on both type and structure, with the compiler verifying every case is covered:

static double area(Shape shape) {
    return switch (shape) {
        case Circle c -> Math.PI * c.radius() * c.radius();
        case Square s -> s.side() * s.side();
        case Triangle t -> 0.5 * t.base() * t.height();
    };
}

No default branch is needed here at all — because Shape is sealed with exactly those three permitted subtypes, the compiler already knows the switch is exhaustive.

Common mistakes

  • Adding a redundant default branch to an exhaustive sealed-type switch "just in case" — if a new subtype is added later, that default would silently swallow it instead of the compiler flagging the switch as needing an update.