TExcelTAD
Home › Java › Java Records

Java Records

Many classes exist only to carry data: a point, a money amount, a row from a database. Writing them the classic way means private final fields, a constructor, getters, equals, hashCode and toString — dozens of lines of boilerplate. Since Java 16, a record declares all of that in a single line.

Your first record

java · try it yourself
record Point(int x, int y) { }

class Main {
    public static void main(String[] args) {
        Point p = new Point(3, 4);
        Point q = new Point(3, 4);
        System.out.println(p);
        System.out.println(p.x() + ", " + p.y());
        System.out.println("equal: " + p.equals(q));
        System.out.println("same object: " + (p == q));
        System.out.println("same hash: " + (p.hashCode() == q.hashCode()));
    }
}
Point[x=3, y=4]
3, 4
equal: true
same object: false
same hash: true

From the header record Point(int x, int y) the compiler generates:

Generated member Example
private final fields x, y
canonical constructor new Point(3, 4)
accessor methods (no get prefix) p.x(), p.y()
equals and hashCode based on all components
toString Point[x=3, y=4]

Records are immutable

All fields are final and there are no setters. To "change" a record you create a new one — often via a small helper method:

java · try it yourself
record Money(long cents, String 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 String.format("%d.%02d %s", cents / 100, cents % 100, currency);
    }
}

class Main {
    public static void main(String[] args) {
        Money price = new Money(1999, "EUR");
        Money shipping = new Money(495, "EUR");
        Money total = price.plus(shipping);
        System.out.println(price + " + " + shipping + " = " + total);
        try {
            price.plus(new Money(100, "USD"));
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
19.99 EUR + 4.95 EUR = 24.94 EUR
Error: Currency mismatch

Records can have methods, static fields and static methods, and you may override generated methods such as toString. They cannot have extra instance fields, and they cannot extend another class (they implicitly extend java.lang.Record), though they can implement interfaces.

Validating with a compact constructor

A compact constructor omits the parameter list and runs before the fields are assigned. It's the place to validate or normalise the values:

java · try it yourself
record Temperature(double celsius) {
    Temperature {
        if (celsius < -273.15) {
            throw new IllegalArgumentException("Below absolute zero: " + celsius);
        }
    }

    double fahrenheit() {
        return celsius * 9 / 5 + 32;
    }
}

record Email(String address) {
    Email {
        address = address.strip().toLowerCase();   // normalise before storing
    }
}

class Main {
    public static void main(String[] args) {
        System.out.println(new Temperature(25).fahrenheit());
        System.out.println(new Email("  Ada@Example.COM "));
        try {
            new Temperature(-300);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
77.0
Email[address=ada@example.com]
Below absolute zero: -300.0

Records with collections and patterns

Because records have proper equals/hashCode, they work great as map keys and set elements. And with record patterns (Java 21) you can take them apart directly in instanceof and switch:

java · try it yourself
import java.util.List;

sealed interface Shape permits Circle, Rect { }
record Circle(double radius) implements Shape { }
record Rect(double width, double height) implements Shape { }

class Main {
    static double area(Shape s) {
        return switch (s) {
            case Circle(double r) -> Math.PI * r * r;
            case Rect(double w, double h) -> w * h;
        };
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Rect(2, 3), new Rect(1.5, 1.5));
        for (Shape s : shapes) {
            System.out.printf("%-30s %.2f%n", s, area(s));
        }
    }
}
Circle[radius=1.0]             3.14
Rect[width=2.0, height=3.0]    6.00
Rect[width=1.5, height=1.5]    2.25

sealed ... permits tells the compiler that Circle and Rect are the only shapes, so the switch is exhaustive without default.

Record or class?

Use a record when... Use a class when...
the type is mainly a carrier of values objects have changing state
equality should mean "same values" identity matters (two accounts with equal data are still different)
immutability is desired you need inheritance from another class

Tip: Records are ideal for DTOs, return values that bundle several results, map keys and messages between parts of a program.

Test yourself

For record User(String name, int age), how do you read the name?

  1. user.getName()
  2. user.name()
  3. user.name
  4. user.get("name")

Which statement about records is true?

  1. Their fields can be reassigned
  2. They can extend any class
  3. They automatically get equals, hashCode and toString
  4. They need a no-arg constructor

What is a compact constructor typically used for?

  1. Adding new fields
  2. Validating or normalising component values
  3. Making the record mutable
  4. Calling super()