Records (Java 16)
Immutable data carriers: compact canonical constructor, with-ers pattern, record limitations
- Replace verbose POJOs with a single-line record declaration
- Customise canonical constructors for validation
- Understand the restrictions of records vs regular classes
Complete Study Guide Chapter: Immutable Data Classes & the Record Type
Table of Contents
- The Problem: Boilerplate in Immutable Classes
- What Is a Record?
- Internal Working: What the Compiler Generates
- Record Components (Fields)
- Constructors in Records
- Accessor Methods (Getters)
- equals(), hashCode(), and toString()
- Adding Custom Methods
- Implementing Interfaces
- Nested Records
- Local Records
- Records vs Lombok
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. The Problem: Boilerplate in Immutable Classes
What Is an Immutable Class?
An immutable class is a class whose instances cannot be modified after creation. All fields are set at construction time and cannot be changed afterward.
Immutable classes are widely used as:
- Data transfer objects (DTOs)
- Value objects
- Configuration holders
- Map keys (because their hash code never changes)
The Pre-Java 16 Way
To write a proper immutable POJO (Plain Old Java Object) in Java before Java 16, you had to manually write all of the following:
1// Pre-Java 16 Immutable User Class2public final class User { // 1. Class must be final3
4 private final String name; // 2. All fields private final5 private final int age;6
7 public User(String name, int age) { // 3. Constructor to initialize all fields8 this.name = name;9 this.age = age;10 }11
12 public String getName() { return name; } // 4. Getter for each field13 public int getAge() { return age; } // 5. No setters allowed14
15 @Override16 public boolean equals(Object o) { // 6. equals() — needed for comparisons,17 if (this == o) return true; // Map keys, Set membership, etc.18 if (!(o instanceof User)) return false;19 User u = (User) o;20 return age == u.age && Objects.equals(name, u.name);21 }22
23 @Override24 public int hashCode() { // 7. hashCode() — consistent with equals()25 return Objects.hash(name, age);26 }27
28 @Override29 public String toString() { // 8. toString() — for debugging and logging30 return "User[name=" + name + ", age=" + age + "]";31 }32}Creating and Using the Object
1User user = new User("Alice", 30);2System.out.println(user.getName()); // Alice3System.out.println(user.getAge()); // 304System.out.println(user); // User[name=Alice, age=30]equals(), hashCode(), and toString().2. What Is a Record?
Definition
A record (introduced in Java 16 as a standard feature, previewed in Java 14/15) is a special kind of class designed to be a transparent, immutable data carrier.
It automatically generates:
- A canonical constructor
- Private final fields for all components
- Accessor methods (getters, named after the fields)
equals(),hashCode(), andtoString()implementations
Syntax
1public record RecordName(Type field1, Type field2, ...) { }That's it. The entire User class from Section 1 becomes:
1public record User(String name, int age) { }Comparison: Old vs New
| Aspect | Pre-Java 16 Immutable Class | Java 16 Record |
|---|---|---|
| Lines of code | ~30+ | 1 |
final class | Manual | Automatic |
private final fields | Manual | Automatic |
| Constructor | Manual | Automatic (canonical) |
| Getters | Manual | Automatic |
| Setters | Not written (manual discipline) | Structurally impossible |
equals() | Manual | Automatic |
hashCode() | Manual | Automatic |
toString() | Manual | Automatic |
| External library needed | Sometimes (Lombok) | No |
Creating and Using a Record
1public record User(String name, int age) { }2
3public class Main {4 public static void main(String[] args) {5 User user = new User("Alice", 30);6
7 System.out.println(user.name()); // Alice (accessor method)8 System.out.println(user.age()); // 309 System.out.println(user); // User[name=Alice, age=30]10 }11}Output
1Alice2303User[name=Alice, age=30]3. Internal Working: What the Compiler Generates
When you write:
1public record User(String name, int age) { }The Java compiler (javac) generates a .class file equivalent to:
1public final class User extends java.lang.Record {2
3 private final String name;4 private final int age;5
6 // Canonical constructor7 public User(String name, int age) {8 this.name = name;9 this.age = age;10 }11
12 // Accessor methods (NOT getters in the traditional getName() style)13 public String name() { return this.name; }14 public int age() { return this.age; }15
16 // Auto-generated equals, hashCode, toString17 @Override18 public boolean equals(Object o) { /* ... */ }19
20 @Override21 public int hashCode() { /* ... */ }22
23 @Override24 public String toString() {25 return "User[name=" + name + ", age=" + age + "]";26 }27}Key Internal Details
1. Record is `final`
The record keyword implicitly makes the class final. You cannot subclass a record.
1public class AdminUser extends User { } // ❌ Compile error — User is final2. All Records Implicitly Extend `java.lang.Record`
Every record you create silently extends java.lang.Record. This is how the JVM knows to apply record semantics.
You can verify this at runtime:
1System.out.println(User.class.getSuperclass()); // class java.lang.Record3. Why You Cannot `extends` Another Class
Because every record already implicitly extends java.lang.Record, and Java does not support multiple class inheritance, you cannot extend any other class.
1public record User(String name, int age) extends MyService { } // ❌ Not allowedextends (for classes) is disallowed.Execution Flow Diagram
4. Record Components (Fields)
What Are Record Components?
The parameters listed in the record header (beside the record name) are called record components. They define the data the record carries.
1public record User(String name, int age) { }2// ─────────────────────3// Record ComponentsThe compiler converts each component into:
- A
private finalfield of the same name and type - A public accessor method of the same name
Transparency Principle
This is why records are called transparent: User(String name, int age) tells you everything.
Cannot Add More Instance Fields Internally
You cannot declare additional instance fields inside the record body:
1public record User(String name, int age) {2 private String email; // ❌ Compile error — instance fields not allowed3}If you need more fields, add them to the record components:
1public record User(String name, int age, String email) { } // ✅Static Fields Are Allowed
While instance fields are forbidden, static fields are permitted inside a record:
1public record User(String name, int age) {2 static final String SPECIES = "Human"; // ✅ Allowed3}Why? Static fields belong to the class, not to any instance. Adding static fields does not affect the immutability of any User object. Each individual User instance still carries only name and age, preserving the transparency guarantee.
1User u1 = new User("Alice", 30);2User u2 = new User("Bob", 25);3// u1 and u2 are fully immutable — SPECIES is shared, not per-object4System.out.println(User.SPECIES); // HumanDefensive Copying for Mutable Fields
private final on a field makes the reference immutable, not the object the reference points to. If a record component is a mutable type (like List, Date, StringBuilder), the record is not truly immutable.1public record User(String name, List<String> hobbies) { }2
3List<String> h = new ArrayList<>(List.of("Reading"));4User user = new User("Alice", h);5
6h.add("Gaming"); // This MODIFIES the list inside the record!7System.out.println(user.hobbies()); // [Reading, Gaming] — compromised!Solution: Defensive copying in the canonical constructor
1public record User(String name, List<String> hobbies) {2 public User(String name, List<String> hobbies) {3 this.name = name;4 this.hobbies = List.copyOf(hobbies); // ✅ Creates an unmodifiable copy5 }6}List.copyOf() creates an unmodifiable list. Any attempt to mutate it throws UnsupportedOperationException.
5. Constructors in Records
Records support three types of constructors.
Type 1: Canonical Constructor (Auto-generated)
The canonical constructor takes all record components as parameters in the exact order they are declared, and initializes all fields.
1public record User(String name, int age) { }2// Implicitly generates:3// public User(String name, int age) {4// this.name = name;5// this.age = age;6// }You do not need to write this — it is generated automatically.
Type 2: Overriding the Canonical Constructor
You can override the canonical constructor to add validation or custom logic:
1public record User(String name, int age) {2
3 // Override canonical constructor4 public User(String name, int age) {5 if (age < 0) {6 throw new IllegalArgumentException("Age cannot be negative: " + age);7 }8 this.name = name;9 this.age = age;10 }11}this.name, this.age, etc.). Failing to do so is a compile error.Type 3: Compact Constructor
The compact constructor is a shorthand form unique to records. You omit the parameter list — the compiler adds it automatically. You also omit the field assignments (this.name = name) — the compiler adds those too, after your body runs.
1public record User(String name, int age) {2
3 // Compact constructor — no parameters, no field assignments needed4 public User {5 if (age < 0) {6 throw new IllegalArgumentException("Age cannot be negative: " + age);7 }8 // this.name = name; and this.age = age; are added automatically by compiler9 }10}This is the cleanest way to add validation to a record.
Canonical vs Compact Constructor Comparison
| Feature | Canonical Constructor | Compact Constructor |
|---|---|---|
| Parameter list | Must list all components | Omit — compiler adds it |
| Field assignments | Must write this.x = x | Omit — compiler adds after body |
| Custom logic | ✅ | ✅ |
| Syntax length | Longer | Shorter |
Type 4: Custom Constructor with Different Parameters
You can add additional constructors with different parameter lists:
1public record User(String name, int age) {2
3 // Custom constructor — age defaults to 04 public User(String name) {5 this(name, 0); // ✅ Must delegate to canonical constructor6 }7}this(...) as its first statement. This ensures all fields are always initialized — no field can be left unset.Constructor Access Level Rules
The access level of the canonical constructor cannot be more restrictive than the record itself:
1public record User(String name, int age) {2 private User(String name, int age) { ... } // ❌ Error — record is public, constructor can't be private3}You can make the canonical constructor equally or more accessible:
1// record is package-private (default) — canonical constructor can be package-private or public2record User(String name, int age) {3 public User(String name, int age) { // ✅ Increasing access is fine4 this.name = name;5 this.age = age;6 }7}Constructor Flow Diagram
6. Accessor Methods (Getters)
Auto-generated Accessors
For every record component, the compiler generates a public accessor method named exactly the same as the field — not in the traditional getXxx() style.
1public record User(String name, int age) { }2
3User user = new User("Alice", 30);4System.out.println(user.name()); // "Alice" — NOT user.getName()5System.out.println(user.age()); // 30 — NOT user.getAge()fieldName(), not getFieldName(). This is a deliberate design choice that distinguishes records from traditional JavaBeans.Overriding Accessors
You can override an accessor to add custom logic:
1public record User(String name, int age) {2
3 @Override4 public String name() {5 return name.trim(); // Custom: trim whitespace before returning6 }7}No Setter Methods
Records never generate setter methods, and you cannot add one:
1public record User(String name, int age) {2 public void setName(String name) {3 this.name = name; // ❌ Compile error — name is final4 }5}The private final fields cannot be reassigned after construction. This is structurally enforced — not just a convention.
7. equals(), hashCode(), and toString()
Auto-generated Implementations
Records automatically generate all three based on all record components:
`equals()`
Two records are equal if and only if they are of the same type and all their record components are equal.
1User u1 = new User("Alice", 30);2User u2 = new User("Alice", 30);3System.out.println(u1.equals(u2)); // true`hashCode()`
The hash code is computed from all record components — consistent with equals().
1System.out.println(u1.hashCode() == u2.hashCode()); // true`toString()`
The format is: RecordName[field1=value1, field2=value2, ...]
1System.out.println(u1); // User[name=Alice, age=30]Overriding Any of These
You can override any of the three if you need custom behavior:
1public record User(String name, int age) {2
3 @Override4 public String toString() {5 return "User: " + name + " (age " + age + ")";6 }7}8
9// Output: User: Alice (age 30)8. Adding Custom Methods
Records are not limited to their auto-generated methods. You can add any instance or static methods:
1public record User(String name, int age) {2
3 // Instance method4 public boolean isAdult() {5 return age >= 18;6 }7
8 // Static method9 public static User anonymous() {10 return new User("Anonymous", 0);11 }12}13
14User u = new User("Alice", 30);15System.out.println(u.isAdult()); // true16
17User anon = User.anonymous();18System.out.println(anon.name()); // Anonymous9. Implementing Interfaces
Records cannot extend other classes (because they already extend java.lang.Record), but they can implement interfaces:
1public interface Printable {2 void print();3}4
5public record User(String name, int age) implements Printable {6
7 @Override8 public void print() {9 System.out.println("User: " + name + ", Age: " + age);10 }11}12
13User u = new User("Alice", 30);14u.print(); // User: Alice, Age: 30You can implement multiple interfaces:
1public record User(String name, int age)2 implements Printable, Serializable { ... }10. Nested Records
Overview
Just as you can have nested classes, you can have nested records — records declared inside another class or record.
Nested Record Is Always Static
static keyword, and you cannot make a nested record non-static.1public record User(String name, int age) {2
3 record Address(String city, String zip) { } // implicitly static4}Accessing a nested record:
1User.Address addr = new User.Address("Mumbai", "400001");2System.out.println(addr.city()); // MumbaiWhy Only Static Nested Records?
This connects to the transparency principle. Consider what would happen if a nested record could be non-static:
- A non-static nested class/record holds an implicit reference to its enclosing instance.
- This means the nested record would secretly carry a reference to the parent record object.
- But that reference would not appear in the nested record's component list.
- This violates transparency: you can no longer tell what data the nested record carries just by reading its declaration.
To prevent this violation, Java mandates that all nested records be static — they have no reference to any enclosing instance, and everything they carry is visible in their component list.
Comparison: Nested Record vs Nested Class vs Non-Static Nested Class
1public record User(String name, int age) {2
3 record NestedAddressRecord(String city) { } // implicitly static nested record4
5 static class StaticAddressClass { } // static nested class6
7 class NonStaticAddressClass { } // non-static nested class (NOT allowed in record)8}Accessing Each Type
1// Static nested record2User.NestedAddressRecord addr1 = new User.NestedAddressRecord("Delhi");3addr1.display();4
5// Static nested class6User.StaticAddressClass addr2 = new User.StaticAddressClass();7addr2.display();8
9// Non-static nested class — requires an enclosing instance10User userObj = new User("Alice", 30);11User.NonStaticAddressClass addr3 = userObj.new NonStaticAddressClass();12addr3.display();11. Local Records
What Is a Local Record?
A local record is a record declared inside a method, constructor, or any block (like an if block or while block). It is analogous to a local class.
1public class Main {2 public static void printAddress() {3
4 // Local record — defined inside a method5 record Address(String city, String zip) {6 void display() {7 System.out.println(city + " - " + zip);8 }9 }10
11 Address addr = new Address("Bangalore", "560001");12 addr.display(); // Bangalore - 56000113 }14
15 public static void main(String[] args) {16 printAddress();17 }18}Rules for Local Records
| Rule | Explanation |
|---|---|
| No access modifiers | Cannot be public, private, or protected — its scope is the enclosing block |
| Scope is the block | Cannot be used outside the block where it is defined |
| Object creation inside block | Can only instantiate the local record within the same block |
| No static modifier | A local record cannot be static — static means "belongs to a class," but a local record's scope ends with the block |
| Is implicitly static | Despite no static keyword, local records are actually implicitly static (like local classes in Java 16+) — they do not capture the enclosing instance |
Why No `static` Keyword on Local Records?
static means something belongs to and persists at the class level. A local record lives only within a block. Once the block finishes executing, the local record is gone. Making it static would be a contradiction — there is no class for it to belong to.
Full Example with Outer Class
1public record User(String name, int age) {2
3 public void printAddress() {4 record Address(String city, String zip) { // local record5 void display() {6 System.out.println(city + " - " + zip);7 }8 }9
10 Address address = new Address("Pune", "411001");11 address.display();12 }13}14
15// Calling from main:16User user = new User("Alice", 30);17user.printAddress(); // Pune - 41100112. Records vs Lombok
A common question: if Lombok already reduces boilerplate, why do we need records?
What Lombok Does
Lombok is a third-party annotation processor that generates boilerplate at compile time using annotations:
1@Getter2@EqualsAndHashCode3@ToString4@AllArgsConstructor5@Value // makes the class immutable (equivalent of all the above combined)6public class User {7 String name;8 int age;9}Head-to-Head Comparison
| Feature | Lombok | Java Records |
|---|---|---|
| External library required | ✅ Yes — add to pom.xml / build.gradle | ❌ No — built into Java |
| IDE plugin needed | Often yes | No |
| Part of the Java spec | No — third-party tool | Yes — JEP 395, Java 16 |
| Prevents setter methods | No — you can write them | Yes — structurally impossible |
| Pattern matching support | No | Yes (instanceof patterns, switch) |
| Sealed class integration | No | Yes |
| Getter naming style | getFieldName() | fieldName() |
| Subclassing restriction | No | Yes — records are implicitly final |
| JVM/reflective recognition | No special JVM treatment | JVM natively identifies records |
| Future enhancements | Depends on Lombok team | Guaranteed via Java evolution |
The Key Differences
1. No External Dependency
Records are a first-class Java language feature. No library in your pom.xml, no IDE plugin, no annotation processor configuration.
2. Structural Enforcement vs Convention
With Lombok's @Value, you could still write a setter method — Lombok wouldn't stop you. With records, you cannot write a setter — the field is final, and the compiler enforces immutability structurally.
1// Lombok @Value — someone could still add:2public void setName(String name) { this.name = name; } // No compile error with Lombok (if @Value allows)3
4// Record — this is a compile error, always:5public record User(String name, int age) {6 void setName(String name) { this.name = name; } // ❌ Compile error7}3. Integration with the Java Ecosystem
Because records are true Java language constructs (not source-level annotation processing tricks), they integrate natively with:
- Pattern matching (
instanceofandswitchwith deconstruction patterns) - Sealed classes and interfaces
- Future Java enhancements
13. Interview Notes
Q1: What is a record in Java?
A record is a special-purpose class introduced in Java 16 that acts as a transparent, immutable data carrier. It auto-generates a canonical constructor, private final fields, accessor methods, and equals(), hashCode(), toString() from a concise declaration.
Q2: What does "transparent data carrier" mean?
It means the record's full data payload is visible just from its declaration. All data a record carries is declared in the record header (record components) — there are no hidden instance fields. You don't need to open the class body to know what the record holds.
Q3: Why can't a record extend another class?
Every record implicitly extends java.lang.Record. Since Java does not support multiple class inheritance, a record cannot extend any additional class. It can, however, implement multiple interfaces.
Q4: What is the difference between the canonical constructor and the compact constructor?
The canonical constructor lists all record components as parameters and explicitly assigns each field. The compact constructor omits both the parameter list and the field assignments — the compiler adds them automatically. The compact constructor is preferred when you just need to add validation.
Q5: What is the naming style of record accessor methods?
Record accessor methods are named exactly as the field: name(), age() — not getName(), getAge(). This distinguishes records from traditional JavaBeans.
Q6: Can you add instance fields inside a record body?
No. Only static fields are permitted inside a record body. Instance fields must be declared as record components in the header. This preserves the transparency principle.
Q7: Why are nested records always static?
If a nested record were non-static, it would implicitly hold a reference to its enclosing record instance. That reference would not appear in the nested record's component list, violating the transparency principle. To prevent this, all nested records are implicitly static.
Q8: Is a record truly immutable if it has a `List` field?
Not by default. private final List makes the reference immutable, but the list contents can still be mutated. For true immutability, you must use defensive copying in the canonical constructor: this.items = List.copyOf(items).
Q9: What is the access level rule for canonical constructors?
The canonical constructor's access level cannot be more restrictive than the record's own access level. You can make the constructor equally or more accessible, but never less.
Q10: How does a record differ from Lombok's `@Value`?
Records are a native Java language feature — no external dependency, structurally enforced immutability, and full integration with pattern matching and sealed classes. Lombok is a third-party annotation processor — it reduces boilerplate but doesn't structurally prevent misuse (e.g., adding setters), and it doesn't participate in JVM-level record recognition or future Java features.
14. Common Mistakes
Mistake 1: Expecting getter methods named `getFieldName()`
1User user = new User("Alice", 30);2user.getName(); // ❌ Compile error — method doesn't exist3user.name(); // ✅ CorrectMistake 2: Trying to add instance fields inside the record body
1public record User(String name, int age) {2 private String email; // ❌ Compile error3}✅ Add to the record components: public record User(String name, int age, String email) { }
Mistake 3: Assuming a record with a `List` field is deeply immutable
1public record Config(List<String> flags) { }2
3List<String> f = new ArrayList<>(List.of("debug"));4Config c = new Config(f);5f.add("verbose"); // Modifies the list inside the record!✅ Use List.copyOf() in the canonical or compact constructor.
Mistake 4: Using `this(...)` call in a custom constructor but not as the first statement
1public record User(String name, int age) {2 public User(String name) {3 System.out.println("Creating user"); // ❌ this() must be first4 this(name, 0);5 }6}✅ this(name, 0) must be the first statement.
Mistake 5: Trying to make a nested record non-static
1public record User(String name, int age) {2 non-static record Address(String city) { } // ❌ Not possible — no such syntax3}All nested records are static. There is no way to make them non-static.
Mistake 6: Giving an access modifier to a local record
1public void myMethod() {2 public record Temp(int value) { } // ❌ Compile error3}✅ Local records cannot have access modifiers — their scope is the enclosing block.
15. Best Practices
- Use records for pure data carriers — DTOs, value objects, API response models, configuration holders.
- Use compact constructors for validation — they are the cleanest way to add precondition checks without verbosity.
1public record Range(int min, int max) {2 public Range {3 if (min > max) throw new IllegalArgumentException("min > max");4 }5}- Apply defensive copying for mutable fields — always wrap
List,Map,Date, and other mutable types with unmodifiable wrappers in the canonical constructor.
- Do not use records for entities that need mutability — if your object needs setters (e.g., JPA entities), use a regular class or Lombok.
- Prefer
recordover Lombok@Valuein Java 16+ projects — native language support, no dependency, structurally enforced immutability.
- Override accessor methods when needed — if you need to return a defensive copy from an accessor, override it:
1public List<String> hobbies() {2 return List.copyOf(hobbies); // Return unmodifiable view3}- Use records with pattern matching (Java 16+) — records integrate natively with
instanceofpattern matching andswitchexpressions for clean deconstruction.
16. Practice Questions
Easy
- What keyword is used to declare a record in Java? Which version introduced it?
- What methods does a record automatically generate?
- What is the naming style of accessor methods in records?
- Can a record extend another class? Can it implement an interface?
- What is a "canonical constructor"?
Medium
- Explain the difference between the canonical constructor and the compact constructor in a record.
- Write a record
Point(double x, double y)with a compact constructor that rejects negative coordinates, and a methoddistanceTo(Point other)that computes the Euclidean distance. - Why are instance fields not allowed inside a record body, but static fields are?
- A colleague uses
public record Config(List. They claim this is immutable. Are they right? How would you fix it?options) { } - What happens if you define a custom constructor in a record that doesn't call
this(...)?
Hard
- Explain why nested records are always implicitly static. What would go wrong if non-static nested records were allowed?
- Compare and contrast Java records with Lombok's
@Value. In what scenarios would you choose one over the other? - Write a record
Money(BigDecimal amount, String currency)with: (a) a compact constructor that validates amount is non-negative and currency is exactly 3 characters, (b) a custom constructorMoney(double amount, String currency)that delegates to the canonical, and (c) a methodadd(Money other)that returns a newMoney(throws if currencies differ). - Explain the rule about canonical constructor access levels. What happens if you try to make the canonical constructor
privatein apublicrecord? - Local records cannot be declared
static. Nested records are alwaysstatic. Explain the reasoning behind each of these seemingly opposite rules.
17. Summary
Revision Bullets
- Records were introduced as a standard feature in Java 16 (JEP 395).
- Syntax:
public record Name(Type field1, Type field2) { }— replaces ~30 lines of boilerplate. - Auto-generates:
private finalfields, canonical constructor,field()accessor methods,equals(),hashCode(),toString(). - A record is implicitly
final— cannot be subclassed. - All records implicitly extend
java.lang.Record— this is whyextends AnotherClassis forbidden. - Records can implement interfaces.
- Record components are declared in the header. No additional instance fields are allowed in the body. Static fields are allowed.
private finalon aListfield makes the reference immutable, not the list contents — useList.copyOf()for deep immutability.- Canonical constructor: takes all components in order; auto-generated; can be overridden.
- Compact constructor: no parameters, no field assignments; compiler adds both; best for validation.
- Custom constructors: allowed with different parameters; must delegate to canonical via
this(...)as the first statement. - Canonical constructor access level cannot be narrower than the record's access level.
- Accessor methods are named
fieldName(), notgetFieldName(). - Nested records are always static — enforces the transparency principle (no hidden enclosing reference).
- Local records have no access modifier, no
statickeyword, and are scoped to their enclosing block. - Records vs Lombok: records are native Java (no library), structurally enforce immutability, integrate with pattern matching and sealed classes.
End of Chapter — Java 16 Records
Mastery check
How well can you recall this?
Finished this lesson?