Records

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Records (Java 16) are a special type of class designed to act as transparent data carriers.
  • They completely eliminate boilerplate code (no need to write getters, constructors, equals(), hashCode(), or toString()).
  • The fields of a record are inherently final and deeply immutable.

Concept

For decades, if you wanted to create a simple class just to hold data (a DTO or Value Object), you had to write 50 lines of boilerplate or rely on external plugins like Lombok.

// OLD WAY: 30 lines of boilerplate for two fields...
public class User {
    private final String name;
    private final int age;
    // Constructor...
    // getName()...
    // getAge()...
    // equals()...
    // hashCode()...
    // toString()...
}

Records solve this natively. By declaring a record, the Java compiler automatically generates a fully immutable class with all the necessary boilerplate perfectly implemented.

Examples

// THIS IS THE ENTIRE CLASS!
public record User(String name, int age) {
    // You can still add custom validation in a "Compact Constructor"
    public User {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
    }
}

public class RecordDemo {
    public static void main(String[] args) {
        
        User user1 = new User("Alice", 30);
        User user2 = new User("Alice", 30);
        
        // 1. Getters are generated without the "get" prefix
        System.out.println(user1.name()); // "Alice"
        
        // 2. equals() is automatically implemented based on field values
        System.out.println(user1.equals(user2)); // true
        
        // 3. toString() is automatically formatted
        System.out.println(user1); // User[name=Alice, age=30]
        
        // user1.name = "Bob"; // ERROR! Fields are implicitly final.
    }
}

Interview Questions

Q: Can a Record extend another class?
A: No. Every Record implicitly extends java.lang.Record. Since Java does not support multiple inheritance, a Record cannot extend any other class. However, a Record can implement multiple Interfaces.

Q: Can you add extra instance variables to a Record?
A: No. All instance variables must be defined in the record header record User(String name). You cannot add private instance fields inside the body of the record. You are, however, allowed to add static fields and static methods.