Pattern matching
suggest changePattern matching is one of the most significant modern enhancements to the Java language. Introduced incrementally across Java 14 through Java 21 LTS, pattern matching removes boilerplate casting, enhances type safety, and enables expressive data-driven programming.
The pattern matching feature set in Java includes:
- Pattern Matching for
instanceof(Java 16) - Pattern Matching for
switch(Java 21) - Record Patterns and Deconstruction (Java 21)
- Guarded Patterns with
when(Java 21)
1. Pattern Matching for instanceof
Prior to Java 16, testing an object's type required an instanceof check followed by an explicit type cast:
// Legacy Java approach (verbose and repetitive)
if (obj instanceof String) {
String s = (String) obj;
System.out.println("Length: " + s.length());
}
With pattern matching, you declare a pattern variable directly in the instanceof expression:
// Modern Java (Java 16+)
if (obj instanceof String s) {
// 's' is automatically in scope and cast
System.out.println("Length: " + s.length());
}
Flow Scoping
Pattern variables use flow scoping: a pattern variable is only in scope where the compiler can guarantee the pattern matched:
public void printPositiveNumber(Object obj) {
// Valid: 'n' is in scope on the right side of '&&' because the left side must be true
if (obj instanceof Integer n && n > 0) {
System.out.println("Positive integer: " + n);
}
// Early exit pattern: 's' remains in scope for the rest of the method!
if (!(obj instanceof String s)) {
return;
}
System.out.println("Uppercase string: " + s.toUpperCase());
}
2. Pattern Matching for switch
Java 21 finalized pattern matching for switch expressions and statements, allowing switch cases to test arbitrary types rather than just primitives, enums, and strings:
public static String formatValue(Object obj) {
return switch (obj) {
case Integer i -> String.format("Integer: %,d", i);
case Long l -> String.format("Long: %,d L", l);
case Double d -> String.format("Double: %.2f", d);
case String s -> "String of length " + s.length() + ": " + s;
case null -> "Null reference";
default -> "Unknown object: " + obj.toString();
};
}
Direct null Handling
Previously, passing null to a switch threw an unconditional NullPointerException. In modern Java, null can be handled explicitly as a case:
switch (input) {
case null -> System.out.println("Null received");
case String s -> System.out.println("String: " + s);
default -> System.out.println("Other: " + input);
}
3. Guarded Patterns with when
You can add arbitrary boolean conditions to a case using the when keyword:
public static String categorize(Object obj) {
return switch (obj) {
case Integer i when i < 0 -> "Negative integer: " + i;
case Integer i when i == 0 -> "Zero";
case Integer i -> "Positive integer: " + i;
case String s when s.isBlank() -> "Blank string";
case String s -> "Non-blank string: " + s;
default -> "Other: " + obj;
};
}
Cases are evaluated in top-to-bottom order. More specific patterns (such as guarded cases) must precede broader fallback patterns.
4. Record Patterns and Nested Deconstruction
Record patterns allow you to deconstruct a record's components directly within an instanceof check or switch branch.
public record Point(int x, int y) {}
public record Circle(Point center, int radius) {}
public record Rectangle(Point topLeft, Point bottomRight) {}
public class Geometry {
public static void printPoint(Object obj) {
// Deconstructs Point into its component variables x and y
if (obj instanceof Point(int x, int y)) {
System.out.println("Point coordinates: x=" + x + ", y=" + y);
}
}
public static double calculateArea(Object shape) {
return switch (shape) {
case Circle(Point(int x, int y), int r) -> Math.PI * r * r;
case Rectangle(Point(int x1, int y1), Point(int x2, int y2)) ->
Math.abs((double)(x2 - x1) * (y2 - y1));
case null -> 0.0;
default -> throw new IllegalArgumentException("Unknown shape: " + shape);
};
}
}
Notice the nested deconstruction: Circle(Point(int x, int y), int r) deconstructs both the outer Circle and the inner Point in a single pattern!
5. Exhaustiveness with Sealed Hierarchies
When pattern matching over a sealed class or interface, the Java compiler inspects all permitted subclasses. If every possible subtype is handled, no default clause is needed:
// Sealed hierarchy
public sealed interface Transaction permits Deposit, Withdrawal, Transfer {}
public record Deposit(double amount) implements Transaction {}
public record Withdrawal(double amount) implements Transaction {}
public record Transfer(double amount, String targetAccount) implements Transaction {}
public class BankProcessor {
public static void process(Transaction tx) {
// Exhaustive switch: No 'default' branch required
switch (tx) {
case Deposit(double amt) ->
System.out.println("Deposited $" + amt);
case Withdrawal(double amt) when amt > 10_000 ->
System.out.println("Flagging large withdrawal: $" + amt);
case Withdrawal(double amt) ->
System.out.println("Withdrawn $" + amt);
case Transfer(double amt, String target) ->
System.out.println("Transferred $" + amt + " to " + target);
}
}
}
Compiler Safety Advantage: If a developer later adds a new permitted subtype Refund to Transaction, the Java compiler will immediately produce a compile error on every un-updated switch, guaranteeing exhaustive handling across your codebase.
6. Summary and Best Practices
- Eliminate manual casts: Replace any
if (x instanceof Y) { Y y = (Y) x; ... }withif (x instanceof Y y). - Prefer Sealed Hierarchies + Pattern Matching: Using sealed types with switch expressions gives compile-time exhaustiveness verification without brittle
defaultcatch-alls. - Order Cases from Specific to General: Always place guarded
whenclauses before general type patterns. - Leverage Record Patterns: Deconstruct records directly in
caselabels to cleanly access nested data without boilerplate accessors.