Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

record

Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().

Available since: Java 16

Syntax

record Name(Type field1, Type field2) { }

Examples

One line instead of a class with a constructor, getters and equals():

record Point(int x, int y) {}
 
void main() {
    var p = new Point(3, 4);
    IO.println(p);
    IO.println(p.x() + p.y());
    IO.println(p.equals(new Point(3, 4)));
}

Output:

Point[x=3, y=4]
7
true

A compact constructor for validation, and custom methods:

record Money(String currency, long cents) {
    Money {
        if (cents < 0) {
            throw new IllegalArgumentException("negative amount");
        }
    }
 
    Money plus(Money other) {
        return new Money(currency, cents + other.cents);
    }
}
 
void main() {
    var total = new Money("EUR", 250).plus(new Money("EUR", 199));
    IO.println(total);
    try {
        new Money("EUR", -1);
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}

Output:

Money[currency=EUR, cents=449]
negative amount

Deconstructing a record in switch and instanceof (record patterns, Java 21):

record Point(int x, int y) {}
 
void main() {
    Object o = new Point(0, 5);
    String where = switch (o) {
        case Point(int x, int y) when x == 0 -> "on the Y axis at " + y;
        case Point(int x, int y) -> "at " + x + ", " + y;
        default -> "not a point";
    };
    IO.println(where);
}

Output:

on the Y axis at 5

Notes

Record fields are private final with no setters; accessors are named like the fields, without get: p.x(), not p.getX(). A record cannot be extended and cannot extend a class, but it can implement interfaces. You can add methods and static fields, but not regular instance fields.

If a field is a mutable object (for example a List), the record is only shallowly immutable: make a copy in the compact constructor, items = List.copyOf(items);.

See also

  • class — Declares a class — a description of objects: their fields and methods.
  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.
  • Object.toString() — Returns a text form of the object; called when printing and when concatenating with a string.
  • sealed / permits — Restricts which classes may extend a class or implement an interface.
  • final — Forbids reassigning a variable, overriding a method or extending a class.

Related recipes

In the tutorial

  • Records — Records in Java: a short class declaration for data, ready-made equals, hashCode and toString, the compact constructor and methods.

Thanks for reading!

Donate to the site — we work hard for you.