Record in Java

What is a Record in Java?

A record is a special kind of class introduced in Java 16 (preview earlier), and fully standard from Java 16 onwards, designed to model immutable data. Think of it as a concise way to define a class whose main purpose is to store data.

A record automatically provides:

  • Final fields
  • Constructor
  • Getters (called accessors)
  • equals(), hashCode(), and toString() methods

Syntax Example (Java 21)

// Define a record
public record Person(String name, int age) {}

// Use the record
public class Main {
    public static void main(String[] args) {
        Person p = new Person("Alice", 30);

        // Access fields
        System.out.println(p.name()); // Alice
        System.out.println(p.age());  // 30

        // toString() is automatically generated
        System.out.println(p);        // Person[name=Alice, age=30]
    }
}

Here:

  • Person is a record with two fields: name and age.
  • p.name() and p.age() are automatically generated accessors.
  • You don’t write constructors or equals/hashCode unless you want custom behavior.

Customizing Records

You can add methods or a custom constructor:

public record Person(String name, int age) {

    // Custom constructor (compact form)
    public Person {
        if (age < 0) throw new IllegalArgumentException("Age must be non-negative");
    }

    // Custom method
    public String greet() {
        return "Hello, " + name + "!";
    }
}

Usage:

Person p = new Person("Bob", 25);
System.out.println(p.greet()); // Hello, Bob!

Key Points About Records

  1. Records are implicitly final — you cannot extend a record.
  2. Fields are private and final by default.
  3. Records are perfect for DTOs, value objects, and immutable data containers.
  4. You can implement interfaces but cannot extend another class.

Leave a Reply