Java Records: Modern Immutable Data Classes & Boilerplate Elimination

For decades, creating simple Data Transfer Objects (DTOs) or immutable value classes in Java required writing extensive repetitive boilerplate: private final fields, constructors, getters, equals(), hashCode(), and toString(). Java Records (finalized in Java 16 LTS) eliminate this friction entirely in a single line of code.

Traditional POJO vs. Modern Java Record

The Old Way: ~50 Lines of Boilerplate POJO:

// Old way: Painful and verbose
public final class StudentDto {
    private final int id;
    private final String name;
    private final String email;

    public StudentDto(int id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }
    public int getId() { return id; }
    public String getName() { return name; }
    public String getEmail() { return email; }
    // ... plus 30 more lines of equals(), hashCode(), and toString()!
}

The Modern Java Way: Exactly 1 Line:

// Modern Java 16+ LTS: 100% equivalent in one line!
public record StudentDto(int id, String name, String email) {}

Using a Record in Action

Notice that record field accessors do NOT use the get prefix; they simply use the field name (e.g. student.name()):

public class RecordDemo {
    public static void main(String[] args) {
        StudentDto s1 = new StudentDto(101, "Aarav Sharma", "aarav@veewom.com");
        StudentDto s2 = new StudentDto(101, "Aarav Sharma", "aarav@veewom.com");

        // 1. Accessing fields via accessor methods:
        System.out.println("Student Name: " + s1.name());

        // 2. Built-in human-readable toString():
        System.out.println(s1); 
        // Output: StudentDto[id=101, name=Aarav Sharma, email=aarav@veewom.com]

        // 3. Built-in value-based equality comparison:
        System.out.println("s1 equals s2: " + s1.equals(s2)); // Output: true!
    }
}

Compact Constructors for Validation

To validate input parameters inside a record, define a Compact Constructor:

public record BankTransfer(String sender, String receiver, double amount) {
    // Compact Constructor (Notice no parameter list!)
    public BankTransfer {
        if (amount <= 0) {
            throw new IllegalArgumentException("Transfer amount must be positive!");
        }
        if (sender == null || receiver == null) {
            throw new NullPointerException("Parties cannot be null!");
        }
        // Automatic assignment occurs immediately after!
    }
}

University Exam Corner (BCA / B.Sc CS)

Exam Question: "Can you declare instance variables inside the body of a Java record?"

Answer: No! A record can ONLY have the instance components declared in its header. You CANNOT declare additional instance fields inside the body (e.g. private int extra; causes a compiler error). However, you CAN declare static fields and methods inside a record body.

Next Step

Congratulations on completing Section 3 (OOP)! Let us proceed to Section 4: Arrays, Strings, Wrappers & Exceptions. Proceed to: Java Arrays (1D & Multi) →

Frequently Asked Questions (FAQ)

Q1. What is a Record in Java?
Introduced as a final feature in Java 16 LTS, a Record is a specialized, compact class designed specifically to act as an immutable data carrier. Declaring a record automatically generates private final fields, a canonical constructor, getters, equals(), hashCode(), and toString().
Q2. Can records inherit other classes in Java?
No! All records in Java implicitly extend 'java.lang.Record' and are implicitly 'final'. Because Java bans multiple class inheritance, a record cannot extend any other class. However, records CAN implement interfaces.
Q3. What is a Compact Constructor in a Java record?
A compact constructor is a constructor in a record that omits the formal parameter list and field assignment statements (e.g. 'public Point { ... }'). It is used purely for argument validation and normalization before automatic assignment.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Classes & Objects →

Standard mutable classes.

Switch Pattern Matching →

Deconstructing records in switch.

Java Encapsulation →

Immutability and data carriers.

Java Arrays →

Entering Section 4: Data structures.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!