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.
// 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()!
}
// Modern Java 16+ LTS: 100% equivalent in one line!
public record StudentDto(int id, String name, String email) {}
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!
}
}
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!
}
}
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.
Congratulations on completing Section 3 (OOP)! Let us proceed to Section 4: Arrays, Strings, Wrappers & Exceptions. Proceed to: Java Arrays (1D & Multi) →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Standard mutable classes.
Deconstructing records in switch.
Immutability and data carriers.
Entering Section 4: Data structures.