Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 201 ยท Object-Oriented Programming

Pattern Matching

Learn Java pattern matching - instanceof patterns, switch with type patterns, case null, guards with when, nested record patterns, exhaustive sealed switches and unnamed _.

Code that handles values of different types often asks the same two questions: "what kind of thing is this?" and "what's inside it?" Old Java answered them with an instanceof test, a cast, and then a series of getter calls, each step repeated by hand. Pattern matching folds all of that into one construct: a pattern tests a value's shape and, if it matches, pulls out the pieces into new variables.

Java added pattern matching in steps: instanceof patterns (Java 16), patterns in switch and record patterns (Java 21), and unnamed variables _ (Java 22). Together with sealed classes and records, they let you write data-processing code that is short, safe and checked by the compiler. This lesson covers each kind of pattern, guards, null handling, the dominance and exhaustiveness rules, and a complete expression evaluator built with nested patterns.

instanceof patterns

Here's the classic test-then-cast idiom and its pattern-matching replacement:

Java
// Before Java 16
if (obj instanceof String) {
    String s = (String) obj;      // cast repeats the type
    IO.println(s.length());
}

// With a type pattern
if (obj instanceof String s) {    // test and bind in one step
    IO.println(s.length());
}

String s here is a type pattern. If obj is a non-null String, the test is true and s holds obj already typed as String. If the test fails, s doesn't exist. There's no cast to get wrong, and the type appears once.

Flow scoping

A pattern variable is in scope wherever the compiler can prove the match succeeded. That's more flexible than ordinary block scope:

Java Where a pattern variable is in scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The two rules to remember:

  • With &&, the binding is usable on the right side, because that side only runs when the left side was true. With || it isn't: obj instanceof String s || s.isEmpty() fails with cannot find symbol, since the right side runs exactly when the match failed.
  • With a negated test (!(x instanceof T t)) whose body always leaves the method (return, throw, break, continue), the variable is in scope after the if. This "guard clause" style keeps the main logic unindented.

instanceof patterns never match null: null instanceof String s is simply false. That makes them a safe replacement for a null check plus a cast.

Patterns in switch

From Java 21, switch accepts patterns as case labels and works on any reference type, not just numbers, strings and enums. Each case tests a pattern, in order, and the first match wins:

Java switch with type patterns, guards and case null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three new features appear here:

  • Type patterns as labels: case Integer i matches when obj is an Integer and binds i.
  • Guards: when adds a boolean condition. case Integer i when i > 0 matches only positive integers; if the guard is false, the switch keeps looking at the next cases. The guard can use the pattern's variables.
  • case null: traditionally, a switch on null throws NullPointerException. A pattern switch can handle null explicitly instead. Without a case null, it still throws, so existing code keeps its behavior. You can combine it with the default: case null, default -> ....

A pattern switch must be exhaustive: every possible value has to match some case. When the selector is Object, only a default (or a total pattern like case Object o) can guarantee that. When it's a sealed type, the list of permitted subtypes is enough, as you'll see below.

Dominance: order matters

Because cases are tried top to bottom, a case that can never be reached is a mistake, and the compiler rejects it:

Java
switch (obj) {
    case CharSequence cs -> IO.println("some text");
    case String s -> IO.println("a string");   // error: this case label is dominated by a preceding case label
    default -> IO.println("other");
}

Every String is a CharSequence, so the second case is dead code. Put the more specific pattern first. Likewise, an unguarded case Integer i dominates any later case Integer i when ..., and default must come after all pattern cases that it would otherwise swallow. The rule of thumb: specific and guarded cases first, general ones last.

Record patterns

A type pattern tells you what a value is. A record pattern also takes it apart. For a record Point(int x, int y), the pattern Point(int x, int y) matches any non-null Point and binds its components directly, by calling the accessors for you:

Java
record Point(int x, int y) { }

if (obj instanceof Point(int x, int y)) {
    IO.println("x + y = " + (x + y));     // no p.x(), p.y() needed
}

The component patterns are themselves patterns, so they nest. That's where record patterns shine: you can match a whole data structure's shape in one line.

Java Nested record patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few details:

  • var in a record pattern lets the compiler infer each component's type from the record. Point(var x1, var y1) binds two ints.
  • Nested patterns can be narrower than the component type. Labeled holds an Object, but Labeled(String label, Point(int x, int y)) only matches when that Object is a Point. If it isn't, the case doesn't match and the switch moves on.
  • Record patterns never match null, at any level. new Line(null, null) matches none of the Line cases above (it would fall to default). A type pattern nested inside a record pattern that covers the component's whole type, such as Object other, does accept a null component.
  • Record patterns work with generic records too: for record Box<T>(T value), you can write case Box<String>(var s) or let the compiler infer case Box(var s).

Exhaustive switches over sealed types

Patterns and sealed types were designed together. When the selector's type is sealed, the compiler knows every possible subtype, so a switch with one case per subtype needs no default. The combination gives you a safe way to write operations over a closed set of data types.

Here's a tiny arithmetic language: an expression is a number, a variable, a sum, a product or a negation. Two operations, eval and simplify, are each one exhaustive switch. simplify uses nested record patterns and guards to recognize algebraic rules like x * 1 = x:

Java An expression evaluator and simplifier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read simplify from top to bottom: the specific rewrite rules come first, the general "simplify the children" cases after them, and the leaves last. Dominance checking makes sure no rule is accidentally unreachable, and exhaustiveness makes sure no kind of expression is forgotten. If you add a Div record to permits, all three methods stop compiling until you handle it.

Exhaustiveness also looks inside record patterns. For a sealed Expr, the cases Neg(Num n) and Neg(Var v) alone don't cover every Neg, but a final case Neg(var inner) does. The compiler works this out for nested sealed types as well.

What if a sealed hierarchy changes but an old compiled switch isn't recompiled? Then the switch may meet a subtype it has never heard of. Instead of silently doing nothing, it throws MatchException at run time. In a normal build where everything is recompiled together, you'll see a compile error first.

Unnamed patterns and variables: _

Patterns often bind variables you don't need. Since Java 22, the underscore _ declares an unnamed pattern variable (or matches any value in a record pattern) without inventing a name:

Java Ignoring components with _

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • In a record pattern, _ alone matches any component: Click(var x, var y, _).
  • case Scroll _, Resize _ -> lists several patterns in one case. That's only allowed when none of them binds a named variable, because the body couldn't know which variables exist.
  • Unnamed variables also work outside patterns: unused loop variables, catch (Exception _), and lambda parameters like (_, value) -> .... See Java Keywords and Identifiers for the rules.

Patterns versus polymorphism

Pattern matching doesn't replace method overriding. If a hierarchy is open and each class has its own behavior, a method that each class overrides is still the cleanest design, and code that switches on types would have to change whenever someone adds a class. Patterns are the better tool when:

  • the set of types is closed (sealed) and the operations keep growing (evaluate, print, simplify, serialize...);
  • the types are plain data (records) that shouldn't know about every operation performed on them;
  • you're handling values whose types you don't control, like an Object coming from a parser or a framework.

A good test: if your switch needs default only because the hierarchy is open, ask whether the type should be sealed, or whether a method on the type would serve better.

Primitive types in patterns (such as case int i or instanceof byte b on an int) are a preview feature in Java 25 and need --enable-preview. Don't use them in production code until they're final.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does describe("") return? String describe(Object o) { return switch (o) { case String s when s.length() > 3 -> "long"; case String s -> "short"; default -> "other"; }; }

    The empty string is a String, but the guard s.length() > 3 is false, so the switch moves on. The next case, an unguarded String pattern, matches.
  2. 2. Which of these compiles?

    After a negated instanceof whose body always returns, n is definitely bound, so it's in scope after the if. The || version can't use s, the CharSequence case dominates the String case, and an Object switch without default isn't exhaustive.
  3. 3. What happens when a pattern switch with no case null receives null?

    For backward compatibility, a switch without case null still throws NullPointerException on null, even if it has a default. Add case null (or case null, default) to handle it.
  4. 4. Given record Pair(Object a, Object b), which value matches case Pair(String s, Integer i)?

    The nested type patterns require a String first and an Integer second. Swapped types don't match, null components don't match narrower type patterns, and a record pattern never matches a null record.
  5. 5. Why can a switch over a sealed interface Expr with one case per permitted record skip default?

    Sealing gives the compiler the full list of possible subtypes. If every one is covered, the switch is exhaustive; adding a new permitted subtype later makes it a compile error.

Summary

  • x instanceof Type t tests and binds in one step; the variable is in scope wherever the match is certain (right of &&, or after a negated test that returns).
  • Pattern switch (Java 21) accepts type patterns, when guards and case null, works on any reference type, and must be exhaustive.
  • Cases are tried in order; the compiler rejects cases dominated by earlier ones, so put specific and guarded cases first.
  • Record patterns like Line(Point(var x1, var y1), var end) deconstruct records and nest; they never match null.
  • Switches over sealed types are exhaustive without default, so adding a subtype turns every unhandled switch into a compile error.
  • _ (Java 22) ignores components and variables; several binding-free patterns can share one case.
  • Use patterns for closed sets of data types and operations that grow; use overriding for open, behavior-rich hierarchies.

Next: The final Keyword Everywhere, where you'll see what final means on variables, parameters, fields, methods and classes.