A record (final in Java 16) is a special kind of class for holding immutable data. You declare only the components, and the compiler generates the private final fields, a constructor, accessor methods, equals(), hashCode() and toString().
Key Points: • record Point(int x, int y) {} replaces roughly 40 lines of a traditional immutable class. • Accessors use the component name without "get": point.x(), not point.getX(). • Records are implicitly final and extend java.lang.Record, so they cannot extend another class, but they can implement interfaces. • You cannot add instance fields, though static fields and methods are allowed. • Good uses: DTOs, API request and response objects, map keys, method results with several values, and events. • Records are shallowly immutable: a List component can still be modified unless you copy it with List.copyOf().
Code Example:
import java.util.HashSet;
import java.util.Set;
public class RecordDemo {
record Employee(String name, String department, double salary) {}
public static void main(String[] args) {
Employee e1 = new Employee("Asha", "Engineering", 95000);
Employee e2 = new Employee("Asha", "Engineering", 95000);
System.out.println(e1); // generated toString()
System.out.println(e1.name() + " earns " + e1.salary());
System.out.println("equals: " + e1.equals(e2)); // compares all components
Set<Employee> set = new HashSet<>();
set.add(e1);
set.add(e2); // same hashCode, so not added again
System.out.println("Set size: " + set.size());
}
}Output:
Employee[name=Asha, department=Engineering, salary=95000.0] Asha earns 95000.0 equals: true Set size: 1
Good to Know: Expect the follow-up "Can records replace JPA entities?" The answer is no. JPA entities need a no-argument constructor, mutable fields and proxies, which records don't allow. Records are a great fit for DTOs and projections instead, for example in Spring Data JPA interface or class-based projections.
Interview Tip: A concise interview answer is:
"A record is a concise, immutable data class: I declare the components, and Java generates private final fields, the constructor, accessors, equals, hashCode and toString. I use records for DTOs, API responses and value objects, but not for JPA entities, which need mutable fields and a no-argument constructor."
Previous question: What is the var keyword in Java 10, and when should you avoid it?
Next question: Can a record have custom constructors, methods and validation?