Skip to content
javahacks.dev
Java Core

Modern Java Guide to Records Sealed Types and Patterns

Write idiomatic Java 25 with records, sealed types, pattern matching, streams and virtual threads, and learn which old habits to drop first.

16 min read
Summarize in AI
Flat illustration of an editor window full of code, with the OpenJDK, Spring, Apache Maven and Gradle logos.

Most Java code in production was written for Java 8, and it shows: getters and setters on every class, instanceof followed by a cast, a visitor with six methods to avoid a type check. Since Java 16 the language has a better answer to each of those, and Java 25, the long-term support release that followed Java 21, finalizes the last pieces you need to write in the new style every day. This guide builds one small payment model on Java 25 and uses it to cover the features worth knowing, in the order you will reach for them. The version floor for each feature is in the sentence that depends on it.

If your project is on Spring, the same style carries over: Spring Boot from first project to production uses records for configuration and DTOs from the first page.

Model values with records

A record declares its components once and the compiler generates the constructor, accessors, equals, hashCode and toString. Records arrived as final in Java 16 (JEP 395).

Money.javajava
public record Money(long cents, String currency) {

    public Money {
        if (cents < 0) {
            throw new IllegalArgumentException("cents must not be negative: " + cents);
        }
        currency = currency.toUpperCase();
    }

    public Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("currency mismatch");
        }
        return new Money(cents + other.cents, currency);
    }
}

The block without parentheses is a compact constructor. It runs before the fields are assigned, so you validate and normalize the parameters there. Assigning to currency changes the parameter, and the field receives the normalized value.

A record is shallowly immutable. The fields cannot be reassigned, but a List component is still a mutable list unless you copy it in the compact constructor with List.copyOf(). That one line is the most common thing people forget.

Use a record for values that are defined by their contents: money, coordinates, an API response. Do not use one for a JPA entity. Hibernate needs a no-argument constructor and mutable state for proxies, and a record has neither (the Hibernate guide covers what to use instead).

Close hierarchies with sealed types

A sealed type lists every class allowed to implement it. Sealed classes became final in Java 17 (JEP 409).

PaymentMethod.javajava
public sealed interface PaymentMethod permits Card, BankTransfer, Voucher {}

record Card(String last4, int expiryYear) implements PaymentMethod {}
record BankTransfer(String iban) implements PaymentMethod {}
record Voucher(String code, long cents) implements PaymentMethod {}

The three records can sit in the same file as the interface, so the compiler can see the whole hierarchy. That is what makes the next step safe.

Branch with pattern matching

Pattern matching for switch and record patterns are final since Java 21 (JEP 441 and JEP 440). A switch over a sealed type needs no default, and adding a fourth payment method breaks the build at every switch that forgot it.

Describe.javajava
static String describe(PaymentMethod method) {
    return switch (method) {
        case Card(String last4, int year) when year < 2026 -> "expired card ending " + last4;
        case Card(String last4, int year) -> "card ending " + last4;
        case BankTransfer(String iban) -> "transfer from " + iban.substring(0, 4);
        case Voucher(String code, long cents) -> "voucher %s worth %d cents".formatted(code, cents);
    };
}

Calling describe(new Card("4242", 2030)) returns card ending 4242. The guarded case must come before the unguarded one for the same type, or the compiler rejects the second as dominated.

The old way was a chain of instanceof checks with casts, or a visitor. The visitor is still right when the hierarchy is open and the operations are closed. A sealed hierarchy flips that: the set of types is fixed and the operations multiply, which is exactly where a switch wins.

Use var where the type is already visible

var has been in the language since Java 10 and only changes what you type, not how the variable is typed.

java
var orders = new ArrayList<Order>();
var total = orders.stream().mapToLong(Order::cents).sum();

The first line is clearer with var because new ArrayList<Order>() says it all. The second is borderline: a reader has to know sum() on a LongStream returns long. When the right-hand side hides the type, write the type.

Streams for transformations, loops for control flow

Streams express a pipeline of transformations. A loop with early exit, mutation or checked exceptions is usually clearer as a loop. A grouped total shows where a stream is the better tool:

Totals.javajava
record Order(String customer, String sku, int quantity, long cents) {}

var orders = List.of(
    new Order("ana", "A-1", 2, 1_500),
    new Order("ana", "B-2", 1, 4_000),
    new Order("ben", "A-1", 5, 1_500));

Map<String, Long> totals = orders.stream().collect(
    Collectors.groupingBy(Order::customer, TreeMap::new,
        Collectors.summingLong(o -> o.quantity() * o.cents())));

System.out.println(totals);
Text
{ana=7000, ben=7500}

Stream.toList(), added in Java 16, returns an unmodifiable list and allows null elements. Collectors.toList() makes no promise about mutability. Pick the first unless a caller needs to add to the result. If you meet the exception that follows from getting this wrong, UnsupportedOperationException on immutable lists walks through it.

Text blocks and the small API upgrades

A text block (final in Java 15) is a multi-line string literal that strips the common indentation, which makes embedded SQL and JSON readable:

java
String sql = """
    SELECT id, name
    FROM customers
    WHERE active = true
    ORDER BY name
    """;

Other additions you will use constantly: List.of() and Map.of() for immutable collections (Java 9), String.isBlank(), strip() and repeat() (Java 11), formatted() (Java 15), and sequenced collections in Java 21, which add getFirst(), getLast() and reversed() to List, Deque and LinkedHashSet.

Threads that do not cost a thread

Virtual threads are final since Java 21 (JEP 444). A virtual thread is scheduled by the JVM on a small pool of carrier threads, and it unmounts while blocked on I/O, so one thread per request stops being a scaling problem.

java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 1_000; i++) {
        int id = i;
        executor.submit(() -> fetchProfile(id));
    }
}

The try block waits for every submitted task on close. Do not pool virtual threads, because they are cheap to create and pooling them defeats the point. Code that spends its time computing gains nothing from them, since the number of carrier threads is bound to your cores. The thread basics post explains the platform thread model they replace.

What Java 25 adds to day-to-day code

Java 25 is a long-term support release. Three of its finalized features change what a small program looks like:

  • Compact source files and instance main methods (JEP 512) let a script or a lesson start without a class declaration or static.
  • Module import declarations (JEP 511) allow import module java.base; to bring in a whole module's exported packages.
  • Flexible constructor bodies (JEP 513) let you validate arguments before calling super(...) or this(...).

None of these should push you to upgrade by itself. The reason to move from 21 to 25 is the support window and the runtime improvements, and the language additions are a bonus. How the runtime turns bytecode into machine code is covered in how the JVM works.

Habits to drop

Old habitModern replacementSince
Class with getters, equals and hashCode for plain datarecordJava 16
instanceof plus castif (o instanceof Card c)Java 16
Visitor over a closed set of typessealed plus switch patternsJava 21
String concatenation for multi-line textText blockJava 15
Collectors.toList() for a read-only resultStream.toList()Java 16
Thread pool sized for blocking I/OVirtual threadsJava 21

Records in daily use

The money example shows the mechanics. Real code uses records in a few recurring ways, and the habits are worth learning together. A record can implement an interface, which lets a value type take part in a hierarchy without a base class. It can have static factory methods, which name the construction paths that a bare constructor cannot, and instance methods for derived values:

java
public record DateRange(LocalDate start, LocalDate end) implements Comparable<DateRange> {

    public DateRange {
        Objects.requireNonNull(start, "start");
        Objects.requireNonNull(end, "end");
        if (end.isBefore(start)) {
            throw new IllegalArgumentException("end " + end + " is before start " + start);
        }
    }

    public static DateRange ofDays(LocalDate start, int days) {
        return new DateRange(start, start.plusDays(days));
    }

    public long days() {
        return ChronoUnit.DAYS.between(start, end);
    }

    public boolean overlaps(DateRange other) {
        return start.isBefore(other.end) && other.start.isBefore(end);
    }

    @Override
    public int compareTo(DateRange other) {
        return start.compareTo(other.start);
    }
}

Because the equality of a record follows its components, a DateRange works as a key in a Map and as an element of a Set with no extra code. Records have no setters, so a change produces a new instance. A small "with" method keeps that readable, and it is better than a builder for records of a handful of components:

java
public record Address(String street, String city, String postalCode) {

    public Address withCity(String newCity) {
        return new Address(street, newCity, postalCode);
    }
}

Nested records are natural for a request or a response. The shape is visible at a glance and each level is validated on its own:

java
public record CreateOrder(String customerId, List<Line> lines, Address shipTo) {

    public record Line(String sku, int quantity) {
        public Line {
            if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive");
        }
    }

    public CreateOrder {
        lines = List.copyOf(lines);               // defensive copy, and rejects nulls
        if (lines.isEmpty()) throw new IllegalArgumentException("an order needs at least one line");
    }
}

Two limits are worth knowing before you adopt records everywhere. A record cannot extend another class, and its fields are final, so it is the wrong fit for anything that a framework must proxy or mutate. And the generated toString prints every component, so a record with a password or a token will print it in a log line unless you override the method. Keep secrets out of records, or override toString.

Pattern matching in the small

The big feature is the switch, and the small one is instanceof with a binding, which removes a cast and a variable. The binding is in scope where the compiler can prove the test passed, and that includes the right side of &&:

java
if (shape instanceof Circle c && c.radius() > 10) {
    return "large circle";
}

if (!(value instanceof String text)) {
    throw new IllegalArgumentException("expected a string but got " + value);
}
return text.strip();                          // text is in scope here, after the early exit

Record patterns deconstruct a value in the pattern and nest, so a method over a small tree reads like the data it handles:

java
sealed interface Expr permits Num, Add, Mul, Neg {}
record Num(double 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 {}

static double evaluate(Expr expr) {
    return switch (expr) {
        case Num(double value) -> value;
        case Add(Expr left, Expr right) -> evaluate(left) + evaluate(right);
        case Mul(Expr left, Expr right) -> evaluate(left) * evaluate(right);
        case Neg(Expr operand) -> -evaluate(operand);
    };
}

static String show(Expr expr) {
    return switch (expr) {
        case Num(var v) -> String.valueOf(v);
        case Add(Num(var a), Num(var b)) -> a + " + " + b;
        case Add(var l, var r) -> "(" + show(l) + " + " + show(r) + ")";
        case Mul(var l, var r) -> show(l) + " * " + show(r);
        case Neg(var o) -> "-" + show(o);
    };
}

There is no default in either method, which is the point: add a Div record and both methods fail to compile until you handle it. The second method shows a nested pattern that matches two numbers directly. When you do not need a component, write an unnamed pattern with _ instead of inventing a name, a feature that is final in recent releases and keeps unused names out of the code:

java
case Add(Num _, Num _) -> "adding two literals";

A switch also handles null on purpose when you ask it to, and a case null replaces a guard clause above the switch:

java
static String label(PaymentMethod method) {
    return switch (method) {
        case null -> "no payment method";
        case Card c -> "card";
        case BankTransfer b -> "transfer";
        case Voucher v -> "voucher";
    };
}

Without the case null, a null selector throws NullPointerException, which is the safe default for code that should never see one.

A result type instead of an exception for expected failures

Sealed interfaces and records make a small result type practical, and it suits the failures that are part of the domain, such as "the card was declined", better than an exception does. The caller cannot forget to handle them, because the compiler checks the switch:

java
public sealed interface Outcome<T> permits Outcome.Success, Outcome.Failure {

    record Success<T>(T value) implements Outcome<T> {}
    record Failure<T>(String code, String message) implements Outcome<T> {}

    static <T> Outcome<T> success(T value) { return new Success<>(value); }
    static <T> Outcome<T> failure(String code, String message) { return new Failure<>(code, message); }
}

Outcome<Receipt> charge(Card card, Money amount) {
    if (card.expired()) {
        return Outcome.failure("CARD_EXPIRED", "The card ended in " + card.last4() + " has expired");
    }
    return Outcome.success(gateway.submit(card, amount));
}

String message = switch (charge(card, amount)) {
    case Outcome.Success<Receipt>(Receipt r) -> "Paid, receipt " + r.reference();
    case Outcome.Failure<Receipt>(String code, String text) -> "Declined (" + code + "): " + text;
};

Keep exceptions for the unexpected: a network failure, a bug, a corrupted file. A result type for a failure a user can cause, and an exception for a failure only an operator can fix, is a split that reads well and tests well. Do not rebuild a general-purpose monad around it. The two-case sealed interface carries most of the value.

Collections and streams, beyond the basics

Immutable collection factories are the default now: List.of, Set.of, Map.of and Map.ofEntries reject nulls and cannot be modified, which removes a class of bugs about who may change a list. When you need an unmodifiable copy of something mutable, use List.copyOf. Sequenced collections in Java 21 add the missing operations at the ends:

java
List<String> steps = new ArrayList<>(List.of("validate", "price", "charge"));
steps.addFirst("authenticate");
String last = steps.getLast();
List<String> reversed = steps.reversed();              // a view, not a copy

A few stream operations are worth knowing because they replace loops with state. Collectors.teeing computes two results in one pass, takeWhile stops at the first failing element and mapMulti replaces a flatMap that would create many tiny streams:

java
record Stats(long count, double average) {}

Stats stats = orders.stream().collect(Collectors.teeing(
    Collectors.counting(),
    Collectors.averagingLong(Order::cents),
    Stats::new));

List<Integer> belowLimit = readings.stream()
    .takeWhile(r -> r < 1000)
    .toList();

List<String> tokens = lines.stream()
    .<String>mapMulti((line, sink) -> {
        for (String token : line.split("\\s+")) {
            if (!token.isBlank()) sink.accept(token);
        }
    })
    .toList();

Stream gatherers, final in Java 24, add custom intermediate operations. Windowing is the example people need most, and it used to require an index or a loop:

java
List<List<Integer>> windows = Stream.of(1, 2, 3, 4, 5, 6, 7)
    .gather(Gatherers.windowFixed(3))
    .toList();                                  // [[1, 2, 3], [4, 5, 6], [7]]

The rule of thumb for streams has not changed. If the pipeline needs mutation of an outer variable, an early return or a checked exception, write the loop. The reader pays for cleverness.

Optional, nulls and the small API changes

Optional is for return types where "no value" is a normal answer, and not for fields, parameters or collections. Use its methods and not isPresent() followed by get():

java
String city = customers.findById(id)
    .map(Customer::address)
    .map(Address::city)
    .orElse("unknown");

customers.findById(id).ifPresentOrElse(
    c -> log.info("found {}", c.name()),
    () -> log.warn("no customer {}", id));

For argument checks, Objects.requireNonNull(value, "name") fails with a message, and Objects.requireNonNullElse(value, fallback) replaces a ternary. The file API is shorter than it was: Files.readString, Files.writeString and Path.of replace most reader and stream boilerplate for small files:

java
String text = Files.readString(Path.of("config.json"));
Files.writeString(Path.of("out.txt"), "done\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

For HTTP, java.net.http.HttpClient has been in the JDK since Java 11, supports HTTP/2 and replaces most uses of a third-party client in simple code:

java
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/ping"))
    .timeout(Duration.ofSeconds(3))
    .header("Accept", "application/json")
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

Concurrency without the thread pool arithmetic

Virtual threads change how you structure concurrent code. The old advice was to size a pool to the work. The new advice is to write blocking code in the straightforward way, start a thread per task and bound what needs bounding with a semaphore or a connection pool:

java
List<Profile> loadProfiles(List<String> ids) throws Exception {
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        List<Future<Profile>> futures = ids.stream()
            .map(id -> executor.submit(() -> profiles.fetch(id)))
            .toList();

        List<Profile> result = new ArrayList<>();
        for (Future<Profile> future : futures) {
            result.add(future.get());
        }
        return result;
    }
}

A thousand profile fetches run concurrently, each on its own virtual thread, and the code reads like a loop. Limit concurrency against a scarce downstream with a Semaphore, not with the size of a pool:

java
Semaphore limit = new Semaphore(20);

Profile fetchLimited(String id) throws InterruptedException {
    limit.acquire();
    try {
        return profiles.fetch(id);
    } finally {
        limit.release();
    }
}

Earlier releases had a caveat: a synchronized block that waited on I/O pinned its carrier thread. Java 24 removed that restriction for monitors, so on a current release the practical limit is native calls and a few specialized cases. Thread-local variables still work with virtual threads, and for per-request data a scoped value is the intended tool, because it is immutable, bounded to a block of code and cheap to inherit by child threads. Structured concurrency, which treats a group of subtasks as one unit that finishes or fails together, is still a preview feature in Java 25, so enable preview in a build only for experiments and plan for the API to change.

Upgrading without drama

Most upgrades fail on the dependency list and not on the language. A method that works for a codebase moving from Java 8 or 11 to 25 in stages:

  1. Move to the next long-term support release first, with --release set to the target in the build, so the compiler rejects APIs newer than you intended.
  2. Run jdeps --jdk-internals --multi-release 25 -R app.jar on the application and its dependencies to find use of JDK internals that newer releases block.
  3. Upgrade the libraries that the report names. Frameworks such as Spring, Hibernate and Jackson publish the minimum Java version for each release.
  4. Run the whole test suite on the new JDK before changing any language feature. A green suite on the new runtime is the baseline.
  5. Adopt features one at a time, in code you are already touching. Convert data classes to records when the class is next edited, not in one commit across the whole repository.
XML
<properties>
  <maven.compiler.release>25</maven.compiler.release>
</properties>

Expect three kinds of breakage: removed or encapsulated APIs, which jdeps finds; changed defaults, such as the character encoding and the default garbage collector, which the release notes list; and libraries compiled with old bytecode tools that do not understand new class file versions. Read the release notes for each long-term support release between your version and the target, since a change that was introduced in an intermediate release is still a change in the one you use.

Where to start in an existing codebase

Do not begin with a rewrite. Begin with the habits in the table above, applied to code that is changing anyway. A pull request that introduces a record for a new DTO, a switch over a sealed type for a new state machine and a text block for a SQL statement teaches the team the idioms with real examples, and the review conversation does the rest. Keep a short list of the old patterns that new code should avoid, put it in the contribution guide, and let a linter or an IDE inspection enforce the ones that are mechanical. In a year the codebase will read as if it were written for the language you run, and the changes will have cost almost nothing, since each was made beside a change that had to happen anyway.

Where this style stops

Records are the wrong tool when you need inheritance, lazy-loaded state or framework proxies: JPA entities, most Spring beans and anything a library subclasses at runtime. A sealed hierarchy is wrong for an extension point that other teams implement, since they cannot add a subtype. And if your libraries or your container still run on Java 11, the first step is the upgrade itself, which starts with fixing [UnsupportedClassVersionError](/library/unsupportedclassversionerror-fix-class-file-version-mismatch) when a dependency was built for a newer release than your runtime.

The errors you will meet on the way are covered one by one: [NullPointerException](/library/nullpointerexception-fix-java-helpful-messages), [ClassCastException](/library/classcastexception-fix-heap-pollution-java) and [ConcurrentModificationException](/library/concurrentmodificationexception-fix-java-collections). For the style rules that go with the features, read clean code in Java.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.