# Records in Java: Concise Immutable Data Carriers

> What are records in Java? What do they generate automatically, what restrictions do they have, and how do they differ from regular classes and Lombok?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-records
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What are records in Java? What do they generate automatically, what restrictions do they have, and how do they differ from regular classes and Lombok?

## Answer

Every Java developer has written a data class: private final fields, a constructor, getters, equals, hashCode and toString, sixty lines of boilerplate to carry two values. Records, finalized in Java 16, exist to kill that boilerplate. A record is a transparent, immutable carrier for a fixed set of values, and you declare it in one line: record Point(int x, int y) {}.

From that header, the compiler generates a lot. It makes a private final field for each component. It creates a canonical constructor taking all components. It creates accessor methods named after the components, so x() and y(), not getX. It generates equals, hashCode and toString based on all components: two records are equal if all their components are equal, and toString prints Point\[x=3, y=4\]. The record class itself is implicitly final and extends java.lang.Record.

You can customize a record. A compact constructor has no parameter list, and lets you validate or normalize the components before the fields are assigned: the assignments happen automatically at the end. For example, checking that a value is not negative and throwing IllegalArgumentException. You can add extra methods, static methods, static fields and additional constructors, but any non-canonical constructor must delegate to another constructor with this(...). You can also override accessors or the generated methods if you need to.

Restrictions worth remembering. A record cannot extend another class (it already extends Record), and it is final, so it cannot be extended. It can implement interfaces, including Comparable. It cannot declare instance fields beyond the components; instance initializers are not allowed either. Its fields are final, so it is shallowly immutable: if a component is a mutable object like a List or an array, the record does not protect its contents. To make it truly immutable, defensively copy in the compact constructor, for example this.items = List.copyOf(items).

Records also shine with modern Java features. Record patterns (Java 21) allow destructuring in instanceof and switch: if (obj instanceof Point(int x, int y)). Combined with sealed interfaces, they give you algebraic data types, so a switch over Shape with Circle and Rectangle records can be checked for exhaustiveness by the compiler. Records are a great fit for DTOs, API responses, map keys (correct equals and hashCode for free), tuple-like return values and stream intermediate results. Local records declared inside a method are handy for grouping in stream pipelines.

How is this different from Lombok? Lombok is a compile-time annotation processor that generates code for ordinary classes, and can produce mutable objects with setters. Records are a language feature, so no dependency is needed, the semantics are standardized, and they are always immutable. They do not replace JPA entities, which need a no-arg constructor and mutable state, nor classes with rich behaviour and hidden state.

Related: serialization of records is safe by design because deserialization always goes through the canonical constructor, so validation cannot be bypassed.

## Code examples

### A validated record

```
import java.util.*;

public class RecordDemo {
    record Point(int x, int y) {
        Point {
            if (x < 0 || y < 0) {
                throw new IllegalArgumentException("negative coordinate");
            }
        }

        double distanceFromOrigin() {
            return Math.sqrt(x * x + y * y);
        }

        static Point origin() {
            return new Point(0, 0);
        }
    }

    record Team(String name, List<String> members) {
        Team {
            members = List.copyOf(members);
        }
    }

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println(p.equals(new Point(3, 4)));
        System.out.println(p.distanceFromOrigin());
        System.out.println(Point.origin().x());

        try {
            new Point(-1, 2);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }

        List<String> src = new ArrayList<>(List.of("Asha"));
        Team t = new Team("Core", src);
        src.add("Ravi");
        System.out.println(t.members());

        Object o = p;
        if (o instanceof Point(int x, int y)) {
            System.out.println(x + y);
        }
    }
}
```

The compact constructor validates input. Team copies the list defensively, so later changes to the source do not affect it. The last block uses a record pattern (Java 21) to destructure the point.

## Key points

- A record generates fields, canonical constructor, accessors, equals, hashCode and toString.
- Records are implicitly final and cannot extend classes, but can implement interfaces.
- Compact constructors validate or normalize components.
- Records are shallowly immutable; copy mutable components defensively.
- They work well with sealed interfaces and pattern matching.

## Common follow-up questions

- Can a record have a no-argument constructor?
- Can records be used as JPA entities?
- What is a compact canonical constructor?
- How do records work with sealed interfaces and switch?

## Interview tips

- Say that accessors are named x(), not getX(); it is a detail that shows hands-on use.
- Call out shallow immutability and the defensive copy fix.

## Concepts covered

Records, Immutability, Compact Constructor, Sealed Types, Pattern Matching

Previous: [Optional: Purpose, Usage and Anti-Patterns](https://www.internhack.in/learn/interview/java-interview/java-optional) · Next: [Tricky Output Questions: Types, Overflow and Overloading](https://www.internhack.in/learn/interview/java-interview/java-tricky-output-basics) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Tricky Output: finally Overrides and Initialization Order](https://www.internhack.in/learn/interview/java-interview/java-tricky-output-finally-init-order)
- [JDK vs JRE vs JVM and Platform Independence](https://www.internhack.in/learn/interview/java-interview/java-jdk-jre-jvm)
- [String Immutability and the String Pool](https://www.internhack.in/learn/interview/java-interview/java-string-immutability-pool)
- [String vs StringBuilder vs StringBuffer](https://www.internhack.in/learn/interview/java-interview/java-string-stringbuilder-stringbuffer)
- [== vs equals() and the hashCode Contract](https://www.internhack.in/learn/interview/java-interview/java-equals-hashcode-contract)
- [final vs finally vs finalize](https://www.internhack.in/learn/interview/java-interview/java-final-finally-finalize)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
