Records

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

TL;DR

  • Records (introduced in Java 14, finalized in Java 16) are a special kind of class designed exclusively to act as transparent, immutable data carriers.
  • They completely eliminate the need for boilerplate code like Getters, equals(), hashCode(), and toString(). The compiler generates them automatically.
  • They are an official alternative to Lombok’s @Data or @Value.

Concept

Historically, to create a simple class that just holds an X and Y coordinate, you had to write 50 lines of code. You needed private final fields, a constructor, getters, and overridden equals, hashCode, and toString methods.

A Record reduces this entire class to a single line:
public record Point(int x, int y) {}

When compiled, the JVM automatically converts this into a final class extending java.lang.Record. It generates the private final fields, the canonical constructor, and all the standard object methods based strictly on the components you defined in the header.

Examples

// 1. Defining a Record
public record UserRecord(int id, String username) {
    
    // 2. Compact Constructor (Optional)
    // You can validate data without restating the parameters!
    public UserRecord {
        if (id < 0) {
            throw new IllegalArgumentException("ID cannot be negative");
        }
        // The JVM implicitly assigns: this.id = id; this.username = username;
    }
    
    // 3. You can add custom methods
    public String getDisplayName() {
        return "@" + username;
    }
}

public class RecordDemo {
    public static void main(String[] args) {
        UserRecord user = new UserRecord(1, "alice");
        
        // 4. Accessing fields (No "get" prefix!)
        System.out.println(user.username()); 
        
        // 5. Automatic toString()
        System.out.println(user); // Prints: UserRecord[id=1, username=alice]
    }
}

Interview Questions

Q: Can a Record extend another class?
A: No. Every Record implicitly extends java.lang.Record. Because Java does not support multiple inheritance, a Record cannot extend any other class. However, a Record can implement interfaces! (e.g., public record User(String name) implements Serializable {}).

Q: Can you add extra instance variables inside a Record?
A: No. All instance variables must be defined in the Record header (the parenthesis after the class name). If you try to declare a private int age; inside the body of the Record, it will not compile. You can, however, define static variables inside the body. This strict limitation ensures that the state of the Record is entirely transparent and immutable.