Video in progress

Junior ☕ Core Java

What is a record, and how does it differ from an ordinary class?

A record (Java 16+) is a short way to write an immutable data-carrier class. The compiler generates the constructor, the private final fields, the accessors, equals, hashCode and toString for you.

📖 Answer

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

This is roughly equal to the following:

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; }   // not getX()!
    public int y() { return y; }
    // equals, hashCode, toString: over all the fields
}

Where it's used:

  • DTOs (API requests/responses);
  • returning several values from a method;
  • Map keys (equals/hashCode come ready-made);
  • events and value objects (Money, Email).

Limitations:

  • the fields are immutable, with no setters;
  • it can't extend another class (it can implement interfaces);
  • it can't be used as a JPA entity.

One catch: a record is not "deeply" immutable. The list inside record Cart(List<Item> items) can be changed from outside, so use List.copyOf(items) in the constructor.