Chapter 64 of 77

Pattern Matching in Java

Very often, a program receives an object and has to ask two questions: "what type is it?" and then "what is inside it?". Before modern Java, answering these questions took three separate steps: check the type, cast, and then pull out the data.

if (obj instanceof String) {           // 1. check the type
    String s = (String) obj;           // 2. cast
    System.out.println(s.length());    // 3. use it
}

We already wrote String twice, and the cast is pure noise: we just checked the type, so of course it is a String. Worse, if someone later edits the check but forgets the cast, the program can throw a ClassCastException.

Pattern matching combines these steps into one.

Pattern matching lets you test whether a value has a certain shape (its type, and optionally its components) and, if it does, automatically extract the parts you need into new variables.

A pattern is the "shape" being tested, such as String s. If the value matches, the variables in the pattern (here s) are filled in for you. These are called pattern variables.

Java added pattern matching step by step over several versions. Everything in this chapter is a standard feature in Java 21 and later, including the current LTS release, Java 25. The only exception is the unnamed pattern _ near the end, which needs Java 22 or later.

Pattern Matching with instanceof (Java 16)

We had a first look at this in the Polymorphism chapter. Instead of a type after instanceof, we write a type and a variable name:

if (obj instanceof String s) {
    System.out.println(s.length());    // s is already a String: no cast needed
}

This is called a type pattern. It reads naturally: "if obj is a String, call it s". Here is a full program that handles different kinds of objects:

class Main {
    public static void main(String[] args) {

        Object[] items = { "Hello", 42, 3.5, 'A' };

        for (Object obj : items) {
            if (obj instanceof String s) {
                System.out.println("String of length " + s.length());
            } else if (obj instanceof Integer i) {
                System.out.println("Integer, doubled = " + (i * 2));
            } else if (obj instanceof Double d) {
                System.out.println("Double, half = " + (d / 2));
            } else {
                System.out.println("Something else: " + obj);
            }
        }
    }
}

Output:

String of length 5
Integer, doubled = 84
Double, half = 1.75
Something else: A

Inside each branch, the pattern variable already has the correct type, so we can call s.length() or do arithmetic on i directly. The 'A' is a Character, which matches none of the patterns, so it reaches the else.

Where Can the Pattern Variable Be Used?

A pattern variable exists only where the compiler is sure the match succeeded. This is called flow scoping. Two common cases are very useful:

  • With &&: the right side runs only if the left side is true, so the variable can be used there.

  • With a negated check and an early return: if the method returns when the match fails, the variable can be used in the rest of the method.

class Main {

    static void checkName(Object obj) {
        // Works with &&: the right side runs only if the match succeeded
        if (obj instanceof String s && s.length() >= 3) {
            System.out.println("Valid name: " + s);
        } else {
            System.out.println("Invalid name: " + obj);
        }
    }

    static void shout(Object obj) {
        if (!(obj instanceof String s)) {
            System.out.println("Not a string, skipping");
            return;
        }
        // Here the compiler knows obj is a String, so s is in scope
        System.out.println(s.toUpperCase() + "!");
    }

    public static void main(String[] args) {
        checkName("Ravi");
        checkName("Al");
        checkName(101);

        shout("hello");
        shout(3.14);
    }
}

Output:

Valid name: Ravi
Invalid name: Al
Invalid name: 101
HELLO!
Not a string, skipping

With ||, however, the right side runs exactly when the match failed, so the variable does not exist there:

if (obj instanceof String s || s.length() > 3) {   // compile error
    System.out.println(s);                         // compile error too
}
error: cannot find symbol
  symbol:   variable s

The same flow-scoping idea makes equals() methods much shorter. Compare this with the hand-written Point class at the start of the Records chapter, which needed a separate check, a cast, and a comparison:

final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof Point p && x == p.x && y == p.y;
    }

    @Override
    public int hashCode() {
        return 31 * x + y;
    }
}

class Main {
    public static void main(String[] args) {
        Point a = new Point(2, 3);
        System.out.println(a.equals(new Point(2, 3)));
        System.out.println(a.equals(new Point(3, 2)));
        System.out.println(a.equals("(2, 3)"));
        System.out.println(a.equals(null));
    }
}

Output:

true
false
false
false

One line does it all. If o is null or not a Point, instanceof is false and the rest is skipped. Remember: instanceof is always false for null, so you never need a separate null check before it.

Pattern Matching in switch (Java 21)

In the Switch Statement chapter, case labels could only be constants like 1, "Monday", or an enum value. Since Java 21, a case can also be a pattern, and you can switch on a value of any reference type, such as Object:

class Main {

    static String describe(Object obj) {
        return switch (obj) {
            case null -> "null value";
            case String s when s.isEmpty() -> "empty string";
            case String s -> "string \"" + s + "\" of length " + s.length();
            case Integer i when i < 0 -> "negative integer " + i;
            case Integer i -> "integer " + i;
            case int[] arr -> "int array with " + arr.length + " elements";
            default -> "something else: " + obj.getClass().getSimpleName();
        };
    }

    public static void main(String[] args) {
        Object[] inputs = { "", "Java", -7, 25, new int[] {1, 2, 3}, 4.5, null };

        for (Object input : inputs) {
            System.out.println(describe(input));
        }
    }
}

Output:

empty string
string "Java" of length 4
negative integer -7
integer 25
int array with 3 elements
something else: Double
null value

This one switch replaces a long chain of if/else if checks. Let's look at the new pieces one by one.

Type patterns in case labels

case String s -> means "if the value is a String, call it s and run this branch". The variable s exists only inside that branch. The cases are tried from top to bottom, and the first one that matches wins.

Guards with when

A when clause adds an extra condition to a pattern. case String s when s.isEmpty() matches only strings that are empty. If the guard is false, Java simply moves on to the next case, which is why "Java" reached the plain case String s. Only pattern labels can have a guard; you cannot write case 5 when ....

case null

A traditional switch throws a NullPointerException when the value is null. A pattern switch does the same, unless it has a case null. Note that default does not match null. If you want both in one branch, you can write case null, default -> ....

default

A switch on Object could receive any type at all, so it needs a default (here it caught the Double). As we'll see shortly, with sealed types you often don't need one.

Order Matters: Dominance

Since cases are checked from top to bottom, a general pattern placed before a more specific one would "steal" all its values. The compiler refuses such code. Every String is a CharSequence, so here the String case could never run:

return switch (obj) {
    case CharSequence cs -> "some text";
    case String s -> "a string";        // can never be reached
    default -> "other";
};
error: this case label is dominated by a preceding case label

The same happens if an unguarded pattern comes before a guarded pattern of the same type:

case Integer i -> "any number";
case Integer i when i > 100 -> "big number";   // dominated

The rule of thumb is: put specific cases first and general cases last. Guarded cases go before the unguarded case of the same type, and default goes at the end.

Sealed Types and Exhaustive switch

A switch expression must cover every possible value, as we saw in the Switch Statement chapter. With an Object, that requires a default. But with a sealed interface (from the Sealed Classes chapter), the compiler knows every permitted subtype, so covering all of them is enough. Here we combine a sealed interface with records:

sealed interface Shape permits Circle, Square, Rectangle {
}

record Circle(double radius) implements Shape {
}

record Square(double side) implements Shape {
}

record Rectangle(double length, double width) implements Shape {
}

class Main {

    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 Rectangle r -> r.length() * r.width();
        };   // no default needed: the compiler knows these are the only three
    }

    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Square(4), new Rectangle(2, 5) };

        for (Shape s : shapes) {
            System.out.printf("%s -> %.2f%n", s, area(s));
        }
    }
}

Output:

Circle[radius=1.0] -> 3.14
Square[side=4.0] -> 16.00
Rectangle[length=2.0, width=5.0] -> 10.00

There is no default, and none is needed. Now suppose someone forgets a case, for example by deleting the Rectangle line:

error: the switch expression does not cover all possible input values

This is the real power of sealed types plus pattern matching. If a new shape such as Triangle is added to the permits list later, every switch that doesn't handle it stops compiling, and the compiler shows you exactly which places to update. If you had written default, the new shape would silently fall into it, and the bug would only show up at runtime. So with sealed types, prefer listing every case over adding a default.

One more rule: as soon as a switch statement uses patterns or case null, it also has to be exhaustive, just like a switch expression. The compiler then reports the switch statement does not cover all possible input values if a case is missing.

Record Patterns (Java 21)

A type pattern checks the type. A record pattern goes one step further: it checks the type and unpacks the record's components into variables, all at once. We had a small preview of this at the end of the Records chapter.

record Point(int x, int y) { }

if (obj instanceof Point(int x, int y)) {
    System.out.println(x + y);     // x and y are the components
}

Record patterns can be nested, so you can unpack a record inside a record. You can also write var instead of the component type and let Java infer it:

record Point(int x, int y) {
}

record Line(Point start, Point end) {
}

class Main {

    static String classify(Point p) {
        return switch (p) {
            case Point(int x, int y) when x == 0 && y == 0 -> "the origin";
            case Point(int x, int y) when y == 0 -> "on the x-axis";
            case Point(int x, int y) when x == 0 -> "on the y-axis";
            case Point(int x, int y) -> "at (" + x + ", " + y + ")";
        };
    }

    static double length(Object obj) {
        // Nested record patterns: unpack a Line AND both of its Points
        if (obj instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
            int dx = x2 - x1;
            int dy = y2 - y1;
            return Math.sqrt(dx * dx + dy * dy);
        }
        return 0;
    }

    public static void main(String[] args) {
        Point[] points = { new Point(0, 0), new Point(5, 0), new Point(0, -2), new Point(3, 4) };

        for (Point p : points) {
            System.out.println(p + " is " + classify(p));
        }

        Line line = new Line(new Point(0, 0), new Point(3, 4));
        System.out.println("Length = " + length(line));
        System.out.println("Length = " + length("not a line"));
    }
}

Output:

Point[x=0, y=0] is the origin
Point[x=5, y=0] is on the x-axis
Point[x=0, y=-2] is on the y-axis
Point[x=3, y=4] is at (3, 4)
Length = 5.0
Length = 0.0

Look at the instanceof in length(). In one condition, it checks that obj is a Line, that both its ends are Points, and extracts all four coordinates. The old way would need a check, a cast, and four accessor calls. For the line from (0, 0) to (3, 4), dx = 3 and dy = 4, so the length is √(9 + 16) = √25 = 5.0.

In classify(), the last case Point(int x, int y) has no guard, so it matches every point. That makes the switch exhaustive without a default. A record pattern never matches null, though; switching on a null point here would throw a NullPointerException.

Unnamed Patterns with _ (Java 22)

Sometimes a pattern must mention a component, but you don't care about its value. Since Java 22, you can write an underscore _ for a variable you don't need:

// Only the x coordinate is needed
if (obj instanceof Point(int x, _)) {
    System.out.println("x = " + x);
}

// Only the type matters, not the object
static String corners(Shape shape) {
    return switch (shape) {
        case Circle _ -> "no corners";
        case Square _, Rectangle _ -> "4 corners";
    };
}

Because _ declares no variable, two patterns like Square _, Rectangle _ can even share one case. This makes it clear to the reader which values are actually used. (In Java 21 this was only a preview feature, disabled by default, so on Java 21 you would write a normal variable name and simply not use it.)

A Complete Example: An Expression Calculator

Sealed interfaces, records, and pattern matching are designed to work together. A classic example is representing a math expression like (2 + 3) * -4 as a tree of small records, and then using switches to evaluate it, print it, and simplify it.

        Mul
       /    \
     Add    Neg
    /   \     \
 Num 2  Num 3  Num 4
sealed interface Expr permits Num, Add, Mul, Neg {
}

record Num(int value) implements Expr {
}

record Add(Expr left, Expr right) implements Expr {
}

record Mul(Expr left, Expr right) implements Expr {
}

record Neg(Expr operand) implements Expr {
}

class Main {

    static int eval(Expr e) {
        return switch (e) {
            case Num(int value) -> value;
            case Add(Expr l, Expr r) -> eval(l) + eval(r);
            case Mul(Expr l, Expr r) -> eval(l) * eval(r);
            case Neg(Expr inner) -> -eval(inner);
        };
    }

    static String show(Expr e) {
        return switch (e) {
            case Num(int value) -> String.valueOf(value);
            case Add(Expr l, Expr r) -> "(" + show(l) + " + " + show(r) + ")";
            case Mul(Expr l, Expr r) -> "(" + show(l) + " * " + show(r) + ")";
            case Neg(Expr inner) -> "(-" + show(inner) + ")";
        };
    }

    static Expr simplify(Expr e) {
        return switch (e) {
            case Mul(Expr l, Num(int v)) when v == 1 -> simplify(l);   // x * 1  =  x
            case Mul(Expr l, Num(int v)) when v == 0 -> new Num(0);    // x * 0  =  0
            case Add(Expr l, Num(int v)) when v == 0 -> simplify(l);   // x + 0  =  x
            case Neg(Neg(Expr inner)) -> simplify(inner);              // -(-x)  =  x
            default -> e;
        };
    }

    public static void main(String[] args) {
        // (2 + 3) * -4
        Expr e1 = new Mul(new Add(new Num(2), new Num(3)), new Neg(new Num(4)));
        System.out.println(show(e1) + " = " + eval(e1));

        // -(-(7 * 1))
        Expr e2 = new Neg(new Neg(new Mul(new Num(7), new Num(1))));
        System.out.println(show(e2) + " = " + eval(e2));
        System.out.println("Simplified: " + show(simplify(e2)));

        // (9 + 0)
        Expr e3 = new Add(new Num(9), new Num(0));
        System.out.println("Simplified: " + show(simplify(e3)));
    }
}

Output:

((2 + 3) * (-4)) = -20
(-(-(7 * 1))) = 7
Simplified: 7
Simplified: 9

Let's trace eval(e1) for (2 + 3) * -4:

eval(Mul(Add(2, 3), Neg(4)))
  = eval(Add(2, 3)) * eval(Neg(4))
  = (eval(Num 2) + eval(Num 3)) * (-eval(Num 4))
  = (2 + 3) * (-4)
  = -20

Some things worth noticing:

  • eval() and show() have no default. Because Expr is sealed, the compiler checks that all four kinds of expression are handled.

  • simplify() uses nested patterns with guards. Mul(Expr l, Num(int v)) when v == 1 means "a multiplication whose right side is the number 1". Neg(Neg(Expr inner)) means "a negation of a negation".

  • For e2, the first matching rule is -(-x) = x, which leaves 7 * 1. Simplifying again applies x * 1 = x, giving 7.

  • simplify() only handles a few special shapes, so it does need a default that returns the expression unchanged.

Programs like compilers, interpreters, and JSON parsers use this exact style. It is often called data-oriented programming: the data is modelled with sealed interfaces and records, and the logic lives in switches over that data.

How Pattern Matching Grew Over Java Versions

Feature

Example

Standard since

Type patterns in instanceof

obj instanceof String s

Java 16

Sealed classes and interfaces

sealed interface Shape permits ...

Java 17

Patterns in switch, when guards, case null

case String s when s.isEmpty() ->

Java 21

Record patterns (including nested)

case Point(int x, int y) ->

Java 21

Unnamed patterns and variables

case Circle _ ->

Java 22

Java is also working on primitive types in patterns (for example, case int i on a double value). It has been available only as a preview feature since Java 23 and is not yet standard, so don't rely on it in normal code or interviews.

Old Style vs Pattern Matching

Task

Old style

With patterns

Check type and use it

instanceof + cast + new variable

obj instanceof String s

Handle many types

Long if/else if chain

One switch with type patterns

Extra conditions

Nested if inside each branch

when guards

Get record components

Call each accessor

Record pattern Point(int x, int y)

Make sure every subtype is handled

Not checked; rely on a default or else

Compiler checks it for sealed types

null handling

Separate if (x == null)

case null

Common Mistakes

  • Using the pattern variable where the match may have failed, for example after || or in the else branch. The compiler reports cannot find symbol.

  • Putting a general case before a specific one. case Object o or case CharSequence cs before case String s is a "dominated" error. Specific first, general last.

  • Expecting default to catch null. It doesn't. Without case null, a null value throws a NullPointerException.

  • Adding a default to a switch over a sealed type. It compiles, but you lose the compile error that would point you to this switch when a new subtype is added.

  • Forgetting the semicolon after a switch expression. return switch (x) { ... }; ends with };.

  • Using these features on an old Java version. Pattern switches and record patterns need Java 21+, and _ needs Java 22+. On Java 17 they don't compile.

Interview Tips

  • What is pattern matching for instanceof? It combines the type check and the cast: if (obj instanceof String s) declares s as a String when the check succeeds. Standard since Java 16.

  • What is a guard? A when condition attached to a pattern case, such as case Integer i when i > 0. The case matches only if the pattern matches and the condition is true.

  • What is dominance? A case label is dominated if an earlier label matches every value it would match. Such code does not compile.

  • Why do sealed classes and pattern matching go together? The compiler knows all permitted subtypes, so a switch can be checked for exhaustiveness without a default.

  • What is a record pattern? A pattern like Point(int x, int y) that matches a record type and extracts its components. Record patterns can be nested. Standard since Java 21.

  • Does instanceof match null? No. null instanceof AnyType is always false.

The Main Idea

Pattern matching lets you check the shape of a value and pull out its parts in a single step, replacing instanceof-cast chains with short, safe, compiler-checked code.

Key points to remember:

  • obj instanceof Type name checks and casts in one go (Java 16).

  • switch can match on types, with when guards and case null (Java 21).

  • Cases are checked top to bottom, so put specific cases first.

  • Record patterns like Point(int x, int y) unpack records, even nested ones (Java 21).

  • With a sealed type, the compiler makes sure every subtype is handled, so you can leave out default.