Records

suggest change

A record is a class whose job is to carry a fixed set of values. You list the values (the components) in the header, and the compiler generates the constructor, accessors, equals, hashCode and toString for you:

record Point(int x, int y) {}

Records became a standard feature in Java 16 (JEP 395). They work well for DTOs, value objects, map keys, returning several values from a method, and the cases of a sealed type hierarchy.

This article covers:

Related articles: Pattern matching and Destructuring cover record patterns in depth, and Immutable Objects covers immutability in general.

All examples are single files you can run with java Example.java. The output shown comes from JDK 25.

A first record

import java.util.HashSet;
import java.util.Set;

public class Basics {
    record Point(int x, int y) {}

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println("x = " + p.x() + ", y = " + p.y());

        Point q = new Point(3, 4);
        System.out.println("p == q:      " + (p == q));
        System.out.println("p.equals(q): " + p.equals(q));
        System.out.println("same hash:   " + (p.hashCode() == q.hashCode()));

        Set<Point> visited = new HashSet<>();
        visited.add(p);
        System.out.println("contains q:  " + visited.contains(q));
    }
}

Output:

Point[x=3, y=4]
x = 3, y = 4
p == q:      false
p.equals(q): true
same hash:   true
contains q:  true

Two records with equal components are equal, so you can use them as HashMap keys or in a HashSet without writing anything else.

The accessors are named x() and y(), not getX() and getY(). Most libraries, including Jackson, Spring and Hibernate Validator, understand this naming.

What the compiler generates

Compile the record and look at it with javap -p:

public record Point(int x, int y) {}
$ javac Point.java && javap -p Point.class
Compiled from "Point.java"
public final class Point extends java.lang.Record {
  private final int x;
  private final int y;
  public Point(int, int);
  public final java.lang.String toString();
  public final int hashCode();
  public final boolean equals(java.lang.Object);
  public int x();
  public int y();
}

For each component the compiler generates a private final field and a public accessor. It also generates a canonical constructor that takes all components in order, plus equals, hashCode and toString based on all components. The class is final and extends java.lang.Record.

Here is the class you would have to write by hand to get the same behaviour:

import java.util.Objects;

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

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

    public int x() { return x; }
    public int y() { return y; }

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

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }

    @Override
    public String toString() {
        return "Point[x=" + x + ", y=" + y + "]";
    }
}

With a record you can't forget a field in equals or let hashCode drift out of sync with it when you add a component.

Validation with a compact constructor

A record should not accept invalid values. Put the checks in a compact constructor. It has no parameter list, and the compiler assigns the fields at the end of it:

public class Validation {
    record Range(int start, int end) {
        Range {
            if (start > end) {
                throw new IllegalArgumentException(
                        "start (%d) must not be after end (%d)".formatted(start, end));
            }
        }

        int length() {
            return end - start;
        }
    }

    record Email(String value) {
        Email {
            value = value.strip().toLowerCase();
            if (!value.contains("@")) {
                throw new IllegalArgumentException("not an email: " + value);
            }
        }
    }

    public static void main(String[] args) {
        Range r = new Range(10, 25);
        System.out.println(r + " length " + r.length());

        System.out.println(new Email("  Alice@Example.COM "));

        try {
            new Range(5, 1);
        } catch (IllegalArgumentException e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}

Output:

Range[start=10, end=25] length 15
Email[value=alice@example.com]
error: start (5) must not be after end (1)

Inside a compact constructor the names start, end and value are the constructor parameters. You can reassign them to normalize the input, as Email does, and the field gets the final value of the parameter. You can't assign the fields yourself:

record Range(int start, int end) {
    Range {
        if (start > end) throw new IllegalArgumentException();
        this.start = start;
    }
}
Bad5.java:4: error: cannot assign a value to final variable start
        this.start = start;
            ^
1 error

You can also write the canonical constructor out in full, with the parameter list. Then you must assign every field yourself:

import java.util.Objects;

public class Canonical {
    record User(String name, int age) {
        // explicit canonical constructor: same parameters as the components
        User(String name, int age) {
            this.name = Objects.requireNonNull(name, "name");
            this.age = age;
        }
    }

    public static void main(String[] args) {
        System.out.println(new User("Ann", 31));
        try {
            new User(null, 5);
        } catch (NullPointerException e) {
            System.out.println("NPE: " + e.getMessage());
        }
    }
}

Output:

User[name=Ann, age=31]
NPE: name

The compact form is shorter and is what you will see in most code.

Records are only shallowly immutable

The fields of a record are final, but the objects they point to can still change. If a component is a mutable List, whoever created the record can change it afterwards:

import java.util.ArrayList;
import java.util.List;

public class DefensiveCopy {
    record LeakyOrder(String id, List<String> items) {}

    record Order(String id, List<String> items) {
        Order {
            items = List.copyOf(items); // immutable copy, also rejects nulls
        }
    }

    public static void main(String[] args) {
        List<String> items = new ArrayList<>(List.of("apple", "pear"));

        LeakyOrder leaky = new LeakyOrder("A1", items);
        Order safe = new Order("A2", items);

        items.add("plum"); // caller changes its list afterwards
        System.out.println(leaky);
        System.out.println(safe);

        try {
            safe.items().add("kiwi");
        } catch (UnsupportedOperationException e) {
            System.out.println("cannot modify: " + e);
        }
    }
}

Output:

LeakyOrder[id=A1, items=[apple, pear, plum]]
Order[id=A2, items=[apple, pear]]
cannot modify: java.lang.UnsupportedOperationException

List.copyOf, Set.copyOf and Map.copyOf return an unmodifiable copy, and they don't copy at all when the argument is already an unmodifiable collection. Use them in the compact constructor for every collection component. For a mutable type with no immutable equivalent, such as java.util.Date, replace it with an immutable one (Instant, LocalDate) rather than copying it.

Constructors, static members and methods

A record body can contain:

Records are immutable, so a "setter" returns a new record instead. These methods are usually called withers:

import java.time.LocalDate;

public class Constructors {
    record Money(long cents, String currency) {
        static final Money ZERO_USD = new Money(0, "USD");

        // non-canonical constructor must delegate to another constructor
        Money(long cents) {
            this(cents, "USD");
        }

        static Money of(String amount, String currency) {
            String[] parts = amount.split("[.]");
            long cents = Long.parseLong(parts[0]) * 100;
            if (parts.length > 1) {
                cents += Long.parseLong((parts[1] + "0").substring(0, 2));
            }
            return new Money(cents, currency);
        }

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

        @Override
        public String toString() {
            return "%d.%02d %s".formatted(cents / 100, cents % 100, currency);
        }
    }

    record Event(String name, LocalDate date) {
        Event withDate(LocalDate newDate) {
            return new Event(name, newDate);
        }
    }

    public static void main(String[] args) {
        Money a = new Money(250);
        Money b = Money.of("19.9", "USD");
        System.out.println(a + " + " + b + " = " + a.plus(b));
        System.out.println(Money.ZERO_USD);

        Event e = new Event("launch", LocalDate.of(2026, 3, 1));
        Event moved = e.withDate(e.date().plusWeeks(2));
        System.out.println(e);
        System.out.println(moved);
    }
}

Output:

2.50 USD + 19.90 USD = 22.40 USD
0.00 USD
Event[name=launch, date=2026-03-01]
Event[name=launch, date=2026-03-15]

Every constructor ends up calling the canonical one, so the validation in a compact constructor can't be bypassed. Inside the record, methods can read the fields directly (cents, other.currency) or through the accessors.

Interfaces and generic records

A record can't extend a class, but it can implement any number of interfaces and it can be generic:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Interfaces {
    record Version(int major, int minor, int patch) implements Comparable<Version> {
        private static final Comparator<Version> ORDER =
                Comparator.comparingInt(Version::major)
                        .thenComparingInt(Version::minor)
                        .thenComparingInt(Version::patch);

        static Version parse(String s) {
            String[] p = s.split("[.]");
            return new Version(Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]));
        }

        @Override
        public int compareTo(Version other) {
            return ORDER.compare(this, other);
        }
    }

    record Pair<A, B>(A first, B second) {
        <C> Pair<A, C> withSecond(C newSecond) {
            return new Pair<>(first, newSecond);
        }
    }

    public static void main(String[] args) {
        List<Version> versions = new ArrayList<>();
        for (String s : List.of("1.10.0", "1.2.3", "2.0.0", "1.2.10")) {
            versions.add(Version.parse(s));
        }
        versions.sort(null); // natural order from compareTo
        versions.forEach(System.out::println);

        Pair<String, Integer> p = new Pair<>("answer", 42);
        Pair<String, Boolean> q = p.withSecond(true);
        System.out.println(p + " -> " + q);
    }
}

Output:

Version[major=1, minor=2, patch=3]
Version[major=1, minor=2, patch=10]
Version[major=1, minor=10, patch=0]
Version[major=2, minor=0, patch=0]
Pair[first=answer, second=42] -> Pair[first=answer, second=true]

Accessor method references such as Version::major work well with Comparator (see Comparable and Comparator).

Prefer a named record to a generic Pair: Pair<String, Integer> says nothing about what the values mean, while record WordCount(String word, int count) does.

Local records and multiple return values

You can declare a record inside a method. A local record is handy for intermediate values in a stream pipeline, such as a composite grouping key:

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LocalRecords {
    record Sale(String region, String product, int units, double price) {}

    public static void main(String[] args) {
        List<Sale> sales = List.of(
                new Sale("EU", "laptop", 3, 1200.0),
                new Sale("US", "laptop", 5, 1100.0),
                new Sale("EU", "phone", 10, 650.0),
                new Sale("US", "phone", 2, 700.0),
                new Sale("EU", "laptop", 1, 1250.0));

        // a local record: visible only inside this method
        record RegionProduct(String region, String product) {}

        Map<RegionProduct, Double> revenue = sales.stream()
                .collect(Collectors.groupingBy(
                        s -> new RegionProduct(s.region(), s.product()),
                        Collectors.summingDouble(s -> s.units() * s.price())));

        revenue.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .forEach(e -> System.out.printf("%-4s %-7s %9.2f%n",
                        e.getKey().region(), e.getKey().product(), e.getValue()));
    }
}

Output:

EU   phone     6500.00
US   laptop    5500.00
EU   laptop    4850.00
US   phone     1400.00

Without the record you would group by a concatenated string like "EU|laptop" and split it again later.

Records also replace Object[] and out-parameters when a method needs to return several values:

import java.util.List;

public class MultiReturn {
    record Stats(int min, int max, double mean) {}

    static Stats stats(List<Integer> values) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        long sum = 0;
        for (int v : values) {
            min = Math.min(min, v);
            max = Math.max(max, v);
            sum += v;
        }
        return new Stats(min, max, (double) sum / values.size());
    }

    public static void main(String[] args) {
        Stats s = stats(List.of(4, 8, 15, 16, 23, 42));
        System.out.println(s);

        // destructure with a record pattern
        if (s instanceof Stats(int min, int max, double mean)) {
            System.out.printf("range %d..%d, mean %.1f%n", min, max, mean);
        }
    }
}

Output:

Stats[min=4, max=42, mean=18.0]
range 4..42, mean 18.0

Records declared inside a class (nested records) are implicitly static, and local records can't capture local variables of the enclosing method. Both rules exist because a record's state must be exactly its components.

Records with sealed interfaces

Records are a natural fit for the cases of a sealed interface. The permits clause lists every implementation, so a switch over the interface can be exhaustive without a default branch, and record patterns pull the components out:

import java.util.List;

public class Sealed {
    sealed interface Shape permits Circle, Rect, Square {}
    record Circle(double radius) implements Shape {}
    record Rect(double width, double height) implements Shape {}
    record Square(double side) implements Shape {}

    static double area(Shape shape) {
        return switch (shape) {
            case Circle(double r) -> Math.PI * r * r;
            case Rect(double w, double h) -> w * h;
            case Square(double s) -> s * s;
        }; // no default needed: the compiler knows all cases are covered
    }

    static String describe(Shape shape) {
        return switch (shape) {
            case Rect(double w, double h) when w == h -> "square-ish rect " + w;
            case Rect r -> "rect " + r.width() + "x" + r.height();
            case Circle c -> "circle r=" + c.radius();
            case Square s -> "square " + s.side();
        };
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Rect(2, 3), new Rect(4, 4), new Square(5));
        for (Shape s : shapes) {
            System.out.printf("%-22s area %.2f%n", describe(s), area(s));
        }
    }
}

Output:

circle r=1.0           area 3.14
rect 2.0x3.0           area 6.00
square-ish rect 4.0    area 16.00
square 5.0             area 25.00

If you later add a Triangle to the sealed interface, every switch that doesn't handle it stops compiling, so the compiler shows you each place you need to update.

A common use is a result type that is either a value or an error. Nesting the records inside the interface keeps them together, and the compiler infers the permits list when all implementations are in the same file:

public class Result {
    sealed interface Parsed<T> {
        record Ok<T>(T value) implements Parsed<T> {}
        record Err<T>(String message, int position) implements Parsed<T> {}
    }

    static Parsed<Integer> parseInt(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (!Character.isDigit(s.charAt(i))) {
                return new Parsed.Err<>("unexpected '" + s.charAt(i) + "'", i);
            }
        }
        return new Parsed.Ok<>(Integer.parseInt(s));
    }

    public static void main(String[] args) {
        for (String input : new String[] {"1234", "12x4"}) {
            String msg = switch (parseInt(input)) {
                case Parsed.Ok<Integer>(var v) -> "ok: " + (v * 2);
                case Parsed.Err<Integer>(var m, var pos) -> "error at " + pos + ": " + m;
            };
            System.out.println(input + " -> " + msg);
        }
    }
}

Output:

1234 -> ok: 2468
12x4 -> error at 2: unexpected 'x'

What records can't do

A record's state is its components and nothing else, so these are compile errors:

Not allowed Why
Instance fields beyond the components State must be exactly the components (static fields are fine)
Assigning a component field The fields are final
extends Every record already extends java.lang.Record
Subclassing a record Records are implicitly final
abstract records Same reason
Instance initializer blocks Use the compact constructor
native methods State must not depend on outside code

Here are the compiler messages for the most common mistakes:

record Counter(int start) {
    private int count;
}
Bad.java:2: error: field declaration must be static
    private int count;
                ^
  (consider replacing field with record component)
record Counter(int start) {
    void increment() {
        start++;
    }
}
Bad2.java:3: error: cannot assign a value to final variable start
        start++;
        ^
record Named(String name) {}

class Special extends Named {
    Special() { super("x"); }
}
Bad3.java:3: error: cannot inherit from final Named
class Special extends Named {
                      ^

If you need mutable state, lazy initialization or inheritance, write a regular class. For the same reason, records don't work as JPA entities: Hibernate needs a no-arg constructor and mutable fields. They do work well as projections and DTOs returned from queries (see JDBC).

Pitfall: array components

The generated equals compares each component with equals, and for arrays that means identity. toString prints the array's type and hash code instead of its contents:

import java.util.Arrays;

public class Arrays1 {
    record Naive(String name, int[] scores) {}

    record Scores(String name, int[] scores) {
        Scores {
            scores = scores.clone();
        }

        @Override
        public int[] scores() {
            return scores.clone(); // don't hand out the internal array
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Scores(String n, int[] s)
                    && name.equals(n) && Arrays.equals(scores, s);
        }

        @Override
        public int hashCode() {
            return 31 * name.hashCode() + Arrays.hashCode(scores);
        }

        @Override
        public String toString() {
            return "Scores[name=" + name + ", scores=" + Arrays.toString(scores) + "]";
        }
    }

    public static void main(String[] args) {
        Naive a = new Naive("ann", new int[] {1, 2, 3});
        Naive b = new Naive("ann", new int[] {1, 2, 3});
        System.out.println(a);
        System.out.println("naive equal: " + a.equals(b));

        Scores c = new Scores("ann", new int[] {1, 2, 3});
        Scores d = new Scores("ann", new int[] {1, 2, 3});
        System.out.println(c);
        System.out.println("fixed equal: " + c.equals(d));
        c.scores()[0] = 99;
        System.out.println("after modifying copy: " + c);
    }
}

Output:

Naive[name=ann, scores=[I@4c9f8c13]
naive equal: false
Scores[name=ann, scores=[1, 2, 3]]
fixed equal: true
after modifying copy: Scores[name=ann, scores=[1, 2, 3]]

Fixing this takes four overrides, and at that point most of the benefit of a record is gone. Usually it is simpler to use List<Integer> with List.copyOf. Keep an array only when performance requires it.

The record pattern o instanceof Scores(String n, int[] s) in equals calls the accessor, so it gets a copy of the array. That is correct, just slightly wasteful.

Reflection

Class.isRecord() and Class.getRecordComponents() let generic code work with any record. Each RecordComponent gives the name, type, accessor method and annotations:

import java.lang.reflect.RecordComponent;
import java.util.LinkedHashMap;
import java.util.Map;

public class Reflect {
    record Book(String title, String author, int year) {}

    static Map<String, Object> toMap(Record r) throws ReflectiveOperationException {
        Map<String, Object> map = new LinkedHashMap<>();
        for (RecordComponent c : r.getClass().getRecordComponents()) {
            map.put(c.getName(), c.getAccessor().invoke(r));
        }
        return map;
    }

    static <T extends Record> T fromMap(Class<T> type, Map<String, Object> map)
            throws ReflectiveOperationException {
        RecordComponent[] comps = type.getRecordComponents();
        Class<?>[] types = new Class<?>[comps.length];
        Object[] values = new Object[comps.length];
        for (int i = 0; i < comps.length; i++) {
            types[i] = comps[i].getType();
            values[i] = map.get(comps[i].getName());
        }
        return type.getDeclaredConstructor(types).newInstance(values);
    }

    public static void main(String[] args) throws Exception {
        Book b = new Book("Dune", "Frank Herbert", 1965);
        System.out.println("isRecord: " + Book.class.isRecord());

        Map<String, Object> map = toMap(b);
        System.out.println(map);

        map.put("year", 1966);
        System.out.println(fromMap(Book.class, map));
    }
}

Output:

isRecord: true
{title=Dune, author=Frank Herbert, year=1965}
Book[title=Dune, author=Frank Herbert, year=1966]

getRecordComponents() returns the components in declaration order, which is also the parameter order of the canonical constructor. Serialization libraries rely on this. See Reflection API for more.

Java serialization

Records can implement Serializable, and they are deserialized differently from ordinary classes: the JVM reads the component values from the stream and then calls the canonical constructor. Your validation runs, so a tampered stream can't create an invalid record:

import java.io.*;

public class Ser {
    record Temperature(double celsius) implements Serializable {
        Temperature {
            if (celsius < -273.15) {
                throw new IllegalArgumentException("below absolute zero: " + celsius);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(new Temperature(21.5));
        }
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            System.out.println("read back: " + in.readObject());
        }

        // tamper with the stream: replace 21.5 with -500.0
        byte[] data = bytes.toByteArray();
        byte[] good = longBytes(Double.doubleToLongBits(21.5));
        byte[] evil = longBytes(Double.doubleToLongBits(-500.0));
        for (int i = 0; i + 8 <= data.length; i++) {
            if (java.util.Arrays.equals(data, i, i + 8, good, 0, 8)) {
                System.arraycopy(evil, 0, data, i, 8);
            }
        }
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            in.readObject();
        } catch (InvalidObjectException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }

    static byte[] longBytes(long v) {
        return java.nio.ByteBuffer.allocate(8).putLong(v).array();
    }
}

Output:

read back: Temperature[celsius=21.5]
rejected: below absolute zero: -500.0

An ordinary Serializable class would have been created with celsius = -500.0, because normal deserialization bypasses constructors. This makes records much safer to deserialize. See Serialization for the general mechanism.

JSON with Jackson

Jackson 2.12 and later, including Jackson 3, map records to and from JSON using the canonical constructor, with no annotations required. Annotations on a component, such as @JsonProperty, apply to the generated field, accessor and constructor parameter:

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import tools.jackson.databind.json.JsonMapper;

public class Json {
    record Address(String city, String country) {}

    record Customer(
            String name,
            @JsonProperty("email_address") String email,
            List<String> tags,
            Address address) {

        Customer {
            tags = tags == null ? List.of() : List.copyOf(tags);
        }
    }

    public static void main(String[] args) {
        JsonMapper mapper = JsonMapper.builder().build();

        Customer c = new Customer("Ann", "ann@example.com", List.of("vip"), new Address("Oslo", "NO"));
        String json = mapper.writeValueAsString(c);
        System.out.println(json);

        String input = """
                {"name":"Bob","email_address":"bob@example.com",
                 "address":{"city":"Lyon","country":"FR"}}
                """;
        Customer back = mapper.readValue(input, Customer.class);
        System.out.println(back);
    }
}

Run it with tools.jackson.core:jackson-databind:3.2.3 and its dependencies on the classpath:

$ java -cp jackson-databind-3.2.3.jar;jackson-core-3.2.3.jar;jackson-annotations-2.22.jar Json.java
{"name":"Ann","email_address":"ann@example.com","tags":["vip"],"address":{"city":"Oslo","country":"NO"}}
Customer[name=Bob, email=bob@example.com, tags=[], address=Address[city=Lyon, country=FR]]

(On Linux and macOS separate classpath entries with : instead of ;.)

The tags field was missing from the input, so Jackson passed null to the constructor, and the compact constructor replaced it with an empty list. Because deserialization goes through the constructor, validation applies to JSON input too. See JSON in Java for more on Jackson.

When to use a record

Use a record when:

Use a regular class when:

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents