Fundamentals 6 min read

Master Java 21’s Switch Pattern Matching and Record Patterns – Simplify Your Code

This article introduces Java 21’s newly finalized switch pattern matching and record patterns, explains their evolution from earlier JDK releases, and provides side‑by‑side code examples that show how these features dramatically reduce boilerplate and improve readability in Java applications.

Programmer DD
Programmer DD
Programmer DD
Master Java 21’s Switch Pattern Matching and Record Patterns – Simplify Your Code

Oracle announced the release of Java 21, the latest long‑term support (LTS) version after JDK 17, bringing thousands of performance, stability, and security improvements, including early access to virtual threads and a vector API that eases AI model development.

The article focuses on two core language enhancements now finalized in JDK 21: switch pattern matching and record patterns.

Switch Pattern Matching

First introduced as a preview in JEP 406 for JDK 17 and refined through JDK 18‑20, switch pattern matching is now fully supported in Java 21, allowing type‑safe case labels and eliminating cumbersome if‑else chains.

Previously, developers had to manually check types and cast objects, as illustrated by the following Map example:

Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);
if (data.get("key1") instanceof String s) {
    log.info(s);
} else if (data.get("key1") instanceof Double d) {
    log.info(d.toString());
} else if (data.get("key1") instanceof Integer i) {
    log.info(i.toString());
}

With switch pattern matching, the same logic becomes concise:

switch (data.get("key1")) {
    case String s -> log.info(s);
    case Double d -> log.info(d.toString());
    case Integer i -> log.info(i.toString());
    default -> log.info("");
}

This reduces boilerplate, especially when dealing with hierarchical or sibling class relationships.

For readers not yet on Java 17, consider also exploring the instance‑of enhancements introduced in Java 16 and the lambda enhancements for switch statements.

Record Patterns

Record patterns were previewed in JDK 19 and refined in JDK 20; Java 21 now finalizes this feature, enabling deconstruction of record values directly in instanceof checks.

Traditional code required explicit casting and field extraction:

record Point(int x, int y) {}

static void printSum(Object obj) {
    if (obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        System.out.println(x + y);
    }
}

Using record patterns, the same operation is reduced to two lines:

static void printSum(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        System.out.println(x + y);
    }
}

The new syntax combines type checking, casting, and deconstruction, dramatically simplifying code.

Follow the Java features column for more updates and deep dives into the latest language improvements.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJava 21pattern-matchingswitchrecord patterns
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.