☕ Java Q76 / 162

What is records feature in Java?

AI-Powered Answer ✓ Answered

Java records, introduced as a preview feature in Java 14 and standardized in Java 16 (JEP 395), are a new type of class designed to act as transparent carriers for immutable data. They aim to significantly reduce the boilerplate code traditionally required for data-carrying classes.

What Are Records?

Records are a special kind of class in Java that provide a concise syntax for declaring classes whose sole purpose is to store data. They are ideal for immutable data transfer objects (DTOs) or value objects where the state is defined by their components.

Key Characteristics and Benefits

  • Conciseness: Records drastically reduce boilerplate code compared to traditional classes for data-centric objects. You only declare the components of the record.
  • Immutability by Default: All components of a record are implicitly final. Once a record is created, its state cannot be changed, promoting safer code.
  • Automatic Method Generation: The Java compiler automatically generates the following methods based on the record's components:
  • * equals() and hashCode(): Based on all components, ensuring proper value equality.
  • * toString(): A human-readable representation of the record and its components.
  • * Canonical Constructor: A constructor that takes all components as arguments.
  • * Accessor Methods: Public methods for each component (e.g., name() for a name component) without the 'get' prefix.
  • Canonical and Compact Constructors: While a canonical constructor is generated, you can define your own to perform validation. A 'compact constructor' allows validation logic without repeating component assignments.
  • No Extensibility: Records implicitly extend java.lang.Record and cannot extend any other class. They are also implicitly final and cannot be extended by other classes, preventing misuse of their data-carrying nature.
  • Serializable: Records are inherently serializable, making them easy to use in various contexts like data persistence or network transfer.

Example

Consider a simple Point class with x and y coordinates. Traditionally, you would write something like this (simplified):

java
public class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    // equals(), hashCode(), toString() methods would also be here
}

With records, the same functionality can be achieved with a single line:

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

This single line implicitly provides:

  • private final int x and private final int y fields.
  • A public canonical constructor: Point(int x, int y).
  • Public accessor methods: int x() and int y().
  • Implementations for equals(), hashCode(), and toString().

When to Use Records

Records are best suited for situations where you need to model immutable data aggregates, such as:

  • Data Transfer Objects (DTOs) for APIs.
  • Value Objects (e.g., coordinates, money amounts).
  • Records used as keys in maps or elements in sets.
  • Temporary tuples or anonymous structs within a method or stream pipeline.

In summary, Java records simplify the creation of data-centric classes, making code more concise, readable, and less error-prone by emphasizing immutability and automatically handling common boilerplate.