Java Records

A record is a class whose whole job is to carry a fixed set of values. You list the components once and the compiler writes the fields, constructor, accessors, equals, hashCode and toString. This page explains what is generated and how, then shows records in real use, their serialization guarantee, and the traps that surprise people moving from ordinary classes.

Contents

What a record is and how it works

Many classes exist only to hold a few values: a point, a money amount, a row from a query, the result of a method that returns two things. Written by hand, such a class needs private final fields, a constructor, getters, equals, hashCode and toString, which is about 50 lines for two fields. A record replaces all of that with one line: record Point(int x, int y) {}.

The list in parentheses is the record's state description, and each entry is a component. A record is defined by its components and nothing else, which is why the language can safely generate everything. From the component list the compiler creates:

  • a private final field per component, and no other instance fields are allowed;
  • a public canonical constructor whose parameters match the components in order;
  • a public accessor per component, named exactly like it: x(), not getX();
  • equals, hashCode and toString that use every component.

Underneath, a record is an ordinary class that is final and extends java.lang.Record. The class file also carries a Record attribute listing the components, which is what reflection reads in getRecordComponents(). The generated equals, hashCode and toString do not contain hand-written bytecode: running javap -c on a record shows that each one is a single invokedynamic instruction linked to java.lang.runtime.ObjectMethods.bootstrap, which receives direct handles to the fields. Two consequences follow, and both are shown running below: these methods read the fields, not your accessors, and the JDK can improve their implementation without recompiling your code.

Record features and when they arrived
FeatureSinceBest for
Records as a preview (JEP 359, then JEP 384)Java 14 and 15Historical only; do not use preview builds for this today
Records final (JEP 395), local records, static members in inner classesJava 16Data carriers, DTOs, map keys, multiple return values
Records in sealed hierarchies (JEP 409)Java 17Closed sets of data types, such as the result of a parser
Record patterns in instanceof and switch (JEP 440, 441)Java 21Taking a record apart into its components

All programs on this page are complete classes, compiled and run on JDK 21. Save one as ClassName.java and run it with java ClassName.java.

The generated members, checked one by one

The program creates two points with the same values, checks each generated member, then uses reflection to confirm what the compiler built and to try to change a field.

Java
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.RecordComponent;
import java.util.HashSet;
import java.util.Set;

public class RecordBasics {

    record Point(int x, int y) {
    }

    public static void main(String[] args) throws Exception {
        Point a = new Point(3, 7);
        Point b = new Point(3, 7);

        System.out.println("accessors:   x()=" + a.x() + ", y()=" + a.y());
        System.out.println("toString:    " + a);
        System.out.println("a == b:      " + (a == b));
        System.out.println("a.equals(b): " + a.equals(b));
        System.out.println("same hash:   " + (a.hashCode() == b.hashCode()));

        Set<Point> set = new HashSet<>(Set.of(a));
        set.add(b);
        System.out.println("set size after adding an equal point: " + set.size());

        // What the compiler generated
        Class<Point> c = Point.class;
        System.out.println("superclass: " + c.getSuperclass().getName());
        System.out.println("final class: " + Modifier.isFinal(c.getModifiers()));
        for (RecordComponent rc : c.getRecordComponents()) {
            Field f = c.getDeclaredField(rc.getName());
            System.out.println("component " + rc.getName() + ": field is "
                    + Modifier.toString(f.getModifiers()));
        }

        // Even reflection cannot change a record field
        Field x = c.getDeclaredField("x");
        x.setAccessible(true);
        try {
            x.setInt(a, 99);
        } catch (IllegalAccessException e) {
            System.out.println("reflective write: IllegalAccessException, x is still " + a.x());
        }
    }
}

Output:

Output
accessors:   x()=3, y()=7
toString:    Point[x=3, y=7]
a == b:      false
a.equals(b): true
same hash:   true
set size after adding an equal point: 1
superclass: java.lang.Record
final class: true
component x: field is private final
component y: field is private final
reflective write: IllegalAccessException, x is still 3
  • a == b is false because there are two objects, but equals is true and the hash codes match because both compare component values. That is why the HashSet still has size 1 after adding the second point.
  • The superclass is java.lang.Record and the class is final. A record cannot extend another class, and nothing can extend a record.
  • Both component fields are private final.
  • setAccessible(true) normally lets reflection write a final field. Records are excluded on purpose, so setInt throws IllegalAccessException and x is still 3. Libraries that create records, such as Jackson and Java serialization, must go through the canonical constructor.

Adding behaviour: methods, static members and local records

A record body can contain instance methods, static fields, static factory methods, nested types and extra constructors, and the record can implement interfaces. The Money record stores cents in a long, so 4.50 + 12.25 + 0.99 adds up exactly, and it implements Comparable. The program also declares a local record inside main.

Java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class RecordFeatures {

    // Records can implement interfaces, declare static members and add methods
    record Money(long cents, String currency) implements Comparable<Money> {

        static final Money ZERO_USD = new Money(0, "USD");

        static Money usd(String amount) {
            return new Money(new BigDecimal(amount).movePointRight(2).longValueExact(), "USD");
        }

        Money plus(Money other) {
            if (!currency.equals(other.currency)) {
                throw new IllegalArgumentException(currency + " vs " + other.currency);
            }
            return new Money(cents + other.cents, currency);   // a new record, never a change
        }

        @Override
        public int compareTo(Money o) {
            return Long.compare(cents, o.cents);
        }

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

    public static void main(String[] args) {
        Money total = Money.ZERO_USD;
        List<Money> items = List.of(Money.usd("4.50"), Money.usd("12.25"), Money.usd("0.99"));
        for (Money m : items) {
            total = total.plus(m);
        }
        System.out.println("total: " + total);
        Money largest = items.stream().max(Comparator.naturalOrder()).orElseThrow();
        System.out.println("largest: " + largest);

        // A local record: a named tuple for an intermediate result inside one method
        record Line(String item, int qty) {
        }
        List<Line> lines = new ArrayList<>(List.of(new Line("pen", 3), new Line("pad", 1)));
        lines.sort(Comparator.comparingInt(Line::qty));
        System.out.println("sorted lines: " + lines);

        try {
            total.plus(new Money(100, "EUR"));
        } catch (IllegalArgumentException e) {
            System.out.println("mixed currencies rejected: " + e.getMessage());
        }
    }
}

Output:

Output
total: USD 17.74
largest: USD 12.25
sorted lines: [Line[item=pad, qty=1], Line[item=pen, qty=3]]
mixed currencies rejected: USD vs EUR
  • The total is exactly USD 17.74: 450 + 1225 + 99 = 1774 cents. usd parses with BigDecimal and longValueExact, so an input with three decimal places throws instead of being rounded silently.
  • plus returns a new Money instead of changing this one. Every "modifying" operation on a record should work this way A method that changes one component is usually named after it, such as withCents(long).
  • max with Comparator.naturalOrder() found USD 12.25 because compareTo compares cents.
  • The local record Line exists only inside main. Local and nested records are implicitly static, so they cannot capture local variables or the enclosing instance.
  • The custom toString replaced the generated one. You can override any generated member, but an override must keep the contract described in the Record Javadoc: a copy made from the accessors must be equal to the original.

Records in everyday code: map keys and multiple return values

The two jobs where records save the most code are composite keys and small result types. The sales list is chosen so that two Oslo 2024 entries must be merged under one key, and so the minimum and maximum come from different cities.

Java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class RecordsInPractice {

    record Sale(String city, int year, int amount) {
    }

    // A composite map key: equals and hashCode come for free
    record CityYear(String city, int year) implements Comparable<CityYear> {
        @Override
        public int compareTo(CityYear o) {
            int c = city.compareTo(o.city);
            return c != 0 ? c : Integer.compare(year, o.year);
        }
    }

    // A generic record used to return two values from one method
    record MinMax<T>(T min, T max) {
    }

    static MinMax<Integer> minMax(List<Integer> values) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int v : values) {
            min = Math.min(min, v);
            max = Math.max(max, v);
        }
        return new MinMax<>(min, max);
    }

    public static void main(String[] args) {
        List<Sale> sales = List.of(
                new Sale("Oslo", 2024, 120), new Sale("Oslo", 2025, 80),
                new Sale("Lima", 2025, 200), new Sale("Oslo", 2024, 30),
                new Sale("Lima", 2025, 50));

        Map<CityYear, Integer> totals = sales.stream().collect(Collectors.groupingBy(
                s -> new CityYear(s.city(), s.year()), TreeMap::new,
                Collectors.summingInt(Sale::amount)));
        totals.forEach((k, v) -> System.out.println(k + " -> " + v));
        System.out.println("lookup Oslo 2024: " + totals.get(new CityYear("Oslo", 2024)));

        MinMax<Integer> mm = minMax(sales.stream().map(Sale::amount).toList());
        System.out.println(mm + ", spread " + (mm.max() - mm.min()));
    }
}

Output:

Output
CityYear[city=Lima, year=2025] -> 250
CityYear[city=Oslo, year=2024] -> 150
CityYear[city=Oslo, year=2025] -> 80
lookup Oslo 2024: 150
MinMax[min=30, max=200], spread 170
  • Oslo 2024 appears twice in the input (120 and 30) and once in the result with 150. groupingBy relies on equals and hashCode of the key, which the record supplies. Before records, the usual shortcut was a string key such as "Oslo|2024", which breaks as soon as a city contains the separator.
  • The lookup with a freshly created new CityYear("Oslo", 2024) finds 150, because a key is found by value, not by identity.
  • The TreeMap sorts by compareTo, so Lima comes before Oslo and 2024 before 2025.
  • MinMax<T> shows that records can be generic. Returning a record is clearer than returning an int[2] or a Map.Entry, because the caller reads mm.max() instead of result[1].

Records are only shallowly immutable

A final field means the reference cannot change. It says nothing about the object it points to. The first part passes a mutable ArrayList into a record and then changes the list. The second part uses arrays, because arrays compare by identity.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ShallowImmutability {

    record Team(String name, List<String> members) {
    }

    record Samples(int[] values) {
    }

    public static void main(String[] args) {
        // The field is final, but the list it points to is not
        List<String> names = new ArrayList<>(List.of("Ana", "Ben"));
        Team team = new Team("core", names);
        names.add("Cho");
        System.out.println("team after caller changed its list: " + team);
        team.members().add("Dev");
        System.out.println("team after changing members():      " + team);

        // Arrays are compared by reference in the generated equals
        Samples s1 = new Samples(new int[] {1, 2, 3});
        Samples s2 = new Samples(new int[] {1, 2, 3});
        System.out.println("records with equal arrays equal: " + s1.equals(s2));
        System.out.println("arrays equal by content:         "
                + Arrays.equals(s1.values(), s2.values()));
        System.out.println("toString shows: " + s1.toString().replaceAll("@\\w+", "@..."));
    }
}

Output:

Output
team after caller changed its list: Team[name=core, members=[Ana, Ben, Cho]]
team after changing members():      Team[name=core, members=[Ana, Ben, Cho, Dev]]
records with equal arrays equal: false
arrays equal by content:         true
toString shows: Samples[values=[I@...]
  • "Cho" appears in the record because the caller kept a reference to the same list. "Dev" appears because members() returns that list too. The fix is a defensive copy, members = List.copyOf(members), in a compact constructor; see record compact constructors.
  • Two records holding identical arrays are not equal, although Arrays.equals says the arrays are. The generated equals calls each component's own equals, and for an array that is ==. toString prints [I@ and an identity hash (shortened here) instead of the numbers. Prefer a List component, or override all three methods with Arrays.equals, Arrays.hashCode and Arrays.toString.

Traps: accessors, floating point and mutable keys

Three behaviours of the generated methods surprise people who know ordinary classes. The program shows each one with the smallest input that triggers it: two codes that differ only in case, the two zeros and NaN, and a list changed after it was used as a key.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RecordPitfalls {

    // An overridden accessor does not change what equals compares
    record Code(String value) {
        @Override
        public String value() {
            return value.toUpperCase();
        }
    }

    record Reading(double celsius) {
    }

    record Basket(List<String> items) {
    }

    public static void main(String[] args) {
        Code lower = new Code("abc");
        Code upper = new Code("ABC");
        System.out.println("accessors: " + lower.value() + " and " + upper.value());
        System.out.println("equal records: " + lower.equals(upper));
        System.out.println("toString: " + lower);

        // double components are compared like Double.compare, not like ==
        System.out.println("0.0 == -0.0:               " + (0.0 == -0.0));
        System.out.println("Reading(0.0) eq (-0.0):    "
                + new Reading(0.0).equals(new Reading(-0.0)));
        System.out.println("NaN == NaN:                " + (Double.NaN == Double.NaN));
        System.out.println("Reading(NaN) eq (NaN):     "
                + new Reading(Double.NaN).equals(new Reading(Double.NaN)));

        // A mutable component changes the hash code of a key already in a set
        List<String> items = new ArrayList<>(List.of("tea"));
        Basket basket = new Basket(items);
        Set<Basket> set = new HashSet<>(Set.of(basket));
        items.add("milk");
        System.out.println("set contains the same basket: " + set.contains(basket));
        System.out.println("set size: " + set.size() + ", iterates to: " + set.iterator().next());
    }
}

Output:

Output
accessors: ABC and ABC
equal records: false
toString: Code[value=abc]
0.0 == -0.0:               true
Reading(0.0) eq (-0.0):    false
NaN == NaN:                false
Reading(NaN) eq (NaN):     true
set contains the same basket: false
set size: 1, iterates to: Basket[items=[tea, milk]]
  • Both accessors return "ABC", yet the records are not equal and toString shows abc. The generated methods read the field, not the accessor, as the invokedynamic design described above implies. If you need normalized values, normalize them in the constructor, not in the accessor.
  • Primitive components are compared the way Double.compare and Float.compare compare, not with ==. So Reading(0.0) and Reading(-0.0) are not equal although 0.0 == -0.0 is true, and two NaN readings are equal although NaN == NaN is false. This keeps equals reflexive, which hash-based collections need.
  • After "milk" is added to the list, the set no longer finds the basket although it still holds it: size 1, and iterating shows [tea, milk]. The hash code changed, so the lookup searches the wrong bucket. A record used as a key must have only immutable components.

Serialization goes through the constructor

Ordinary Serializable classes are rebuilt without calling any constructor, so the checks in a constructor can be bypassed by crafted bytes. Records were given different rules: the stream stores only the component values, and deserialization calls the canonical constructor with them. The program serializes a record and a classic class, each with a constructor that prints when it runs.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class RecordSerialization {

    record Range(int lo, int hi) implements Serializable {
        Range {
            System.out.println("  Range constructor runs for " + lo + ".." + hi);
            if (lo > hi) {
                throw new IllegalArgumentException("lo > hi");
            }
        }
    }

    static class OldRange implements Serializable {
        private static final long serialVersionUID = 1L;
        final int lo;
        final int hi;

        OldRange(int lo, int hi) {
            System.out.println("  OldRange constructor runs for " + lo + ".." + hi);
            this.lo = lo;
            this.hi = hi;
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("creating:");
        Range r = new Range(1, 5);
        OldRange o = new OldRange(1, 5);

        System.out.println("deserializing the record:");
        Range r2 = (Range) roundTrip(r);
        System.out.println("  result " + r2 + ", equal: " + r.equals(r2));

        System.out.println("deserializing the class:");
        OldRange o2 = (OldRange) roundTrip(o);
        System.out.println("  result lo=" + o2.lo + " hi=" + o2.hi + " (no constructor call)");
    }

    static Object roundTrip(Object value) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(value);
        }
        try (ObjectInputStream in =
                new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            return in.readObject();
        }
    }
}

Output:

Output
creating:
  Range constructor runs for 1..5
  OldRange constructor runs for 1..5
deserializing the record:
  Range constructor runs for 1..5
  result Range[lo=1, hi=5], equal: true
deserializing the class:
  result lo=1 hi=5 (no constructor call)

The record's constructor ran twice, once when the program created it and once during readObject. The class's constructor ran only once: deserialization filled in its fields directly. For a record, a validation such as lo > hi therefore also protects data read from a file or socket. Records also ignore serialVersionUID matching and custom readObject or writeObject methods, so the serialized form is exactly the component list. More on the classic mechanism is in object serialization.

Which one to use

Records compared with the alternatives
NeedRecordRegular classLombok @Value
Extend another classNo, always extends RecordYesYes
Be subclassedNo, implicitly finalYes, unless finalNo, final by default
Extra instance fieldsNoYesYes
Hide the internal representationNo, every component has a public accessorYesNo, a getter per field by default
Generated equals, hashCode, toStringYes, by the languageNoYes, by an annotation processor
Deconstruct with record patternsYesNoNo
Safe deserialization through the constructorYesNoNo
  • Use a record when the type is its data: coordinates, money, DTOs, query results, events, map keys, results with several values.
  • Keep a regular class when the object has changing state, when its identity matters (an open connection, an entity tracked by an ORM), or when its fields are an implementation detail that might change.
  • JPA entities cannot be records, because JPA needs a no-argument constructor and mutable fields. Records work well for the projections and DTOs around them.

Next steps: validating and normalizing components in compact constructors, taking records apart with record patterns, and combining them into closed hierarchies with sealed classes.