Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 201 ยท Object-Oriented Programming

Records

Learn Java records - what the compiler generates, compact constructors for validation, shallow immutability, static factories, local records and when to use them.

A lot of classes exist only to carry data: a point with x and y, a money amount with a currency, a row from a CSV file. Writing one by hand means private final fields, a constructor, getters, equals, hashCode and toString, about 40 lines in which a single typo in equals causes bugs that are hard to find. A record (Java 16) declares the same class in one line:

Java
record Point(int x, int y) {}

From that line the compiler generates everything a correct, immutable data class needs. Records aren't just shorter: they make a promise that the object is exactly its data, nothing more, which lets readers, tools and features like pattern matching rely on that. This lesson covers what records generate, how to validate and normalize data in a compact constructor, the limits of their immutability, extra methods and factories, local records, and when a record is the right tool.

What a record gives you

The names in parentheses are the record's components. For each component, the compiler generates:

  • a private final field with the same name;
  • a public accessor method with the same name: x(), not getX();

and for the record as a whole:

  • a public canonical constructor taking all components in order;
  • equals that compares every component;
  • hashCode consistent with equals;
  • toString that prints the record name and all components.
Java Everything a one-line record generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

a and b are different objects (== is false), but they hold the same data, so they're equal and have the same hash code. That makes records ideal as keys in a HashMap or elements of a HashSet, which is why visited.contains(new Point(3, 4)) finds the point. Writing that correctly by hand is the topic of The Object Class: equals, hashCode and toString; a record does it for you.

The generated toString prints Point[x=3, y=4]. That format is meant for debugging and logs, not for user-facing text, and you can override it.

The rules records follow

A record is a restricted kind of class. The restrictions are what make its promise trustworthy:

  • Records are final. You can't extend a record, and a record can't extend a class (it implicitly extends java.lang.Record).
  • Component fields are final. There are no setters; once created, a record's fields never change.
  • No extra instance fields. All state is declared in the header. Writing private int cache; inside a record body fails with field declaration must be static.
  • Records can implement interfaces, and they can have static fields, static methods, instance methods, nested types and additional constructors.
Java
record Range(int start, int end) implements Comparable<Range> {
    static final Range EMPTY = new Range(0, 0);   // static field: fine

    int length() {                                // instance method: fine
        return end - start;
    }

    @Override
    public int compareTo(Range other) {
        return Integer.compare(length(), other.length());
    }
}

Records declared inside another class are implicitly static, so you can create them without an instance of the outer class, as in the Main example above.

Compact constructors: validate and normalize

Usually you don't want every combination of values to be allowed. A temperature below absolute zero, a negative quantity or a blank email address should be rejected at the moment the object is created. Records let you add checks with a compact constructor: a constructor with no parameter list that runs before the fields are assigned.

Java Validating and normalizing in a compact constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Inside a compact constructor, the names celsius and address refer to the constructor's parameters. After the body finishes, the compiler assigns each parameter to its field automatically. That's why normalizing works: reassigning the parameter address changes what gets stored. You may not write this.address = ... yourself; the field is assigned for you, and assigning it in a compact constructor is a compile error.

Because every record is created through the canonical constructor, a check there guarantees that no invalid record can ever exist. Normalization also makes equality meaningful: the two emails differing only in case are equal.

You can also write the canonical constructor in full form, with parameters and explicit this.x = x; assignments. Use that only when you need it; the compact form is shorter and can't forget a field.

Shallow immutability and defensive copies

A record's fields are final, but final only means the field always refers to the same object. If that object is mutable, like an ArrayList or an array, its contents can still change:

Java A mutable list inside a record, and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

LeakyTeam shares the caller's list, so adding "Grace" later silently changes the "immutable" record. Team copies the list in its compact constructor with List.copyOf, which returns an unmodifiable list, so the record is truly immutable. For maps and sets use Map.copyOf and Set.copyOf. Immutable Classes explains why this matters for thread safety and map keys.

Arrays in records are a trap. The generated equals compares components with equals, and arrays inherit identity-based equals from Object. So new Data(new int[]{1, 2}).equals(new Data(new int[]{1, 2})) is false, and toString prints something like [I@1b6d3586. Prefer a List component; if you must use an array, copy it in the constructor and accessor and override equals, hashCode and toString with Arrays.equals and friends.

Adding methods, factories and "withers"

A record body can contain anything a class can, except instance fields. Typical additions are:

  • Derived values computed from components (length(), total()), instead of storing them.
  • Static factory methods with descriptive names, like Money.of(...) or Point.origin().
  • Extra constructors, which must delegate to the canonical one with this(...).
  • "With" methods that return a modified copy, since you can't change a record in place.
  • Overridden accessors or toString, when the defaults aren't right.
Java A Money record with factories and copy methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every "change" returns a new Money, and every new Money passes through the compact constructor, so the rules (3-letter code, two decimal places) can't be bypassed. The last line is true because both amounts were normalized to scale 2. Using BigDecimal for money instead of double is explained in BigInteger and BigDecimal.

Local records

You can declare a record inside a method. A local record is visible only in that method, which is perfect for an intermediate result that has no meaning elsewhere, such as pairing a value with something computed from it so you can sort or filter:

Java A local record for an intermediate result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Local records are implicitly static: they can't use the enclosing method's local variables, which keeps them simple data carriers. (Local enums and interfaces are allowed for the same reason since Java 16.) The stream code is covered in Streams; method references like WordStats::vowels work naturally because accessors are ordinary methods.

Records and pattern matching

Because a record is exactly its components, Java can take it apart for you. A record pattern matches a record and binds its components to variables in one step:

Java
Object shape = new Point(3, 4);

if (shape instanceof Point(int x, int y)) {
    IO.println("distance from origin: " + Math.hypot(x, y));
}

Combined with switch and sealed interfaces, record patterns let you model data like "a payment is a card, a transfer or cash" and handle every case safely. Pattern Matching covers this in depth.

When to use a record

Use a record when an object is defined by its values:

  • Values with meaning: Point, Money, Email, DateRange, Coordinates.
  • Returning several values from a method (Parameters and Return Values).
  • Keys in maps and elements in sets, where correct equals/hashCode is essential.
  • Data transfer objects (DTOs) for JSON, API responses and query results.
  • Messages and events passed between parts of a program.

Use a regular class when:

  • The object has identity and changing state: a bank account whose balance changes, a game character that moves. (You can model changes with "with" methods, but a mutable object is sometimes clearer.)
  • You need inheritance, or state that isn't part of the public data (caches, internal counters).
  • A framework requires a no-argument constructor and setters. JPA entities (Advanced Java) are the classic example, although records work well for JPA query results and DTOs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given record Book(String title, int pages) {}, which call reads the title?

    Record accessors have the same name as the component, with no get prefix. The field itself is private.
  2. 2. What does this print? record P(int x) {} ... IO.println(new P(1).equals(new P(1)) + " " + (new P(1) == new P(1)));

    equals compares the components, so the records are equal, but == compares references and they are two separate objects.
  3. 3. Inside a compact constructor of record Name(String value), you write value = value.strip();. What is stored in the field?

    In a compact constructor the component names are the parameters, and the compiler assigns them to the fields after your code runs, so normalization works.
  4. 4. A record has a List<String> component and a caller keeps adding to the list it passed in. How do you make the record truly immutable?

    Record fields are final, but that's shallow. List.copyOf creates an unmodifiable copy, so neither the caller nor anyone using the accessor can change it.
  5. 5. Which of these can a record declare?

    Records may add static and instance methods, static fields and constructors, but no extra instance fields, no superclass and no way to change components.

Summary

  • record Name(Type a, Type b) {} declares an immutable data class with private final fields, accessors a()/b(), a canonical constructor, and equals, hashCode and toString based on all components.
  • Records are final, can't extend classes and can't declare extra instance fields, but they can implement interfaces and add methods, static members and constructors (which must call this(...)).
  • A compact constructor validates and normalizes data; reassign the parameters, and the compiler stores them in the fields.
  • Record immutability is shallow: copy mutable components with List.copyOf and friends, and avoid array components.
  • Use static factories and "with" methods to create modified copies; use local records for intermediate results inside a method.
  • Choose records for values defined by their data; use classes for objects with identity, changing state or inheritance.

Next: Enums, where you'll define types with a fixed set of named values, which can carry data and behavior just like records.