Many classes in real programs exist only to carry data: a point with x and y, a student with a name and marks, a product with a name and price. For such a simple class, we still end up writing a lot of code: private fields, a constructor, getters, equals(), hashCode(), and toString().
Here is a "simple" class holding just two numbers:
final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
int getX() { return x; }
int getY() { return y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return java.util.Objects.hash(x, y);
}
@Override
public String toString() {
return "Point[x=" + x + ", y=" + y + "]";
}
}That's over 25 lines for two numbers. Since Java 16, we can write the same thing in one line using a record:
record Point(int x, int y) { }A record is a special kind of class for holding immutable data. You list the fields once, and Java automatically generates the constructor, accessor methods, equals(), hashCode(), and toString().
What Java Generates for You
For record Point(int x, int y) { }, the compiler creates:
private final int x; ← one private final field per component
private final int y;
Point(int x, int y) ← the "canonical" constructor
int x() ← accessor methods (no "get" prefix!)
int y()
equals(Object) ← true if all components are equal
hashCode() ← based on all components
toString() ← Point[x=3, y=4]The values listed in the brackets, int x and int y, are called the record's components.
Using a Record
import java.util.HashSet;
record Point(int x, int y) {
}
class Main {
public static void main(String[] args) {
Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
System.out.println(p1);
System.out.println(p1.x() + ", " + p1.y());
System.out.println(p1 == p2);
System.out.println(p1.equals(p2));
System.out.println(p1.hashCode() == p2.hashCode());
HashSet<Point> visited = new HashSet<>();
visited.add(p1);
System.out.println(visited.contains(new Point(3, 4)));
}
}Output:
Point[x=3, y=4]
3, 4
false
true
true
trueLet's go through this:
toString()prints the record name and every component, which is very handy for debugging.The accessors are called
x()andy(), notgetX()andgetY().p1 == p2isfalsebecause they are two different objects in memory.p1.equals(p2)istruebecause records compare by value: all components are equal.Because
equals()andhashCode()are correct, records work perfectly asHashSetelements andHashMapkeys. Storing grid cells asPointrecords in avisitedset is a very common pattern in coding problems.
Records Are Immutable
All fields of a record are final. There are no setters, and you cannot assign to a field after the object is created:
record Point(int x, int y) {
void moveRight() {
this.x = x + 1; // compile error
}
}error: cannot assign a value to final variable xIf you need a "changed" point, create a new one:
record Point(int x, int y) {
Point moveRight() {
return new Point(x + 1, y);
}
}Immutable objects are easier to reason about and are safe to share between different parts of a program (and between threads, which you will learn about later).
Validation with a Compact Constructor
What if we want to reject invalid data, such as marks above 100? Records support a special compact constructor. It has no parameter list, and Java assigns the fields automatically at the end of it:
record Student(String name, int marks) {
Student {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Invalid marks: " + marks);
}
name = name.trim();
}
boolean hasPassed() {
return marks >= 40;
}
static Student absent(String name) {
return new Student(name, 0);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student(" John ", 85);
System.out.println(s1);
System.out.println(s1.hasPassed());
Student s2 = Student.absent("Alex");
System.out.println(s2 + " passed? " + s2.hasPassed());
try {
new Student("Jason", 120);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Output:
Student[name=John, marks=85]
true
Student[name=Alex, marks=0] passed? false
Error: Invalid marks: 120Notice three things:
Inside the compact constructor,
nameandmarksare the parameters. Changingname(we trimmed it) changes the value that is stored in the field.A record can have its own instance methods like
hasPassed().A record can have static methods (and static fields) like
absent().
You can also write the full canonical constructor with this.name = name; lines, or add extra constructors, but every extra constructor must call another constructor using this(...).
Records and Interfaces
A record cannot extend another class (it already extends java.lang.Record), but it can implement interfaces. For example, we can give a record a natural order using Comparable from the previous chapters:
import java.util.ArrayList;
import java.util.Collections;
record Product(String name, double price) implements Comparable<Product> {
@Override
public int compareTo(Product other) {
return Double.compare(this.price, other.price);
}
}
class Main {
public static void main(String[] args) {
ArrayList<Product> cart = new ArrayList<>();
cart.add(new Product("Keyboard", 1499.0));
cart.add(new Product("Mouse", 599.0));
cart.add(new Product("Monitor", 8999.0));
Collections.sort(cart);
for (Product p : cart) {
System.out.println(p.name() + " - Rs. " + p.price());
}
}
}Output:
Mouse - Rs. 599.0
Keyboard - Rs. 1499.0
Monitor - Rs. 8999.0Rules and Restrictions
Records are deliberately limited so that they stay simple data carriers:
Rule | Why |
|---|---|
A record is implicitly | No class can extend a record |
A record cannot extend a class | It already extends |
All component fields are | Records are immutable |
No extra instance fields allowed | The components are the complete state |
Static fields and methods are allowed | They don't belong to individual objects |
A nested record is implicitly | It does not hold a reference to an outer object |
For example, adding an instance field is an error:
record Point(int x, int y) {
int z; // compile error
}error: field declaration must be static
(consider replacing field with record component)A Common Trap: Shallow Immutability
A record makes its fields final, but it does not freeze the objects those fields point to. If a component is a mutable list, the list can still change:
import java.util.ArrayList;
import java.util.List;
record Team(String name, List<String> members) {
}
record SafeTeam(String name, List<String> members) {
SafeTeam {
members = List.copyOf(members); // store an unmodifiable copy
}
}
class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("John");
Team team = new Team("Alpha", list);
list.add("Alex");
System.out.println(team.members());
SafeTeam safe = new SafeTeam("Beta", list);
list.add("Priya");
System.out.println(safe.members());
try {
safe.members().add("Jason");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify: " + e.getClass().getSimpleName());
}
}
}Output:
[John, Alex]
[John, Alex]
Cannot modify: UnsupportedOperationExceptionThe Team record "changed" when the outside list changed, because it stored a reference to the same list. SafeTeam makes a defensive, unmodifiable copy with List.copyOf(), so later changes to the original list do not affect it, and nobody can modify its members.
Record Patterns (Java 21+)
In newer Java versions (Java 21 and later, including the current LTS release, Java 25), records also work with record patterns, which let you check the type and pull out the components in one step:
Object obj = new Point(3, 4);
if (obj instanceof Point(int x, int y)) {
System.out.println("Sum = " + (x + y));
}Output:
Sum = 7You don't need this feature yet, but you will see it in modern Java code, especially together with switch.
Record vs Normal Class vs Enum
Feature | Normal class | Record | Enum |
|---|---|---|---|
Purpose | Anything (data + behaviour) | Immutable data carrier | Fixed set of constants |
Number of objects | Unlimited | Unlimited | Fixed, listed in the enum |
Mutable fields | Allowed | Not allowed | Allowed, but discouraged |
equals/hashCode/toString | Write yourself | Generated (by value) | Provided by |
Can extend a class | Yes | No | No |
When to use a record: for DTOs (data transfer objects), API responses, coordinates, map keys, returning multiple values from a method, and any "just data" object. When not to: when the object needs to change over time (like a BankAccount whose balance changes) or needs to extend another class.
The Main Idea
A record is a concise, immutable data class. Write
record Name(components) { }and Java generates the fields, constructor, accessors, equals(), hashCode(), and toString() for you.
Key points to remember:
Records were added as a standard feature in Java 16.
Accessors use the component name:
p.x(), notp.getX().Two records with the same component values are
equals().Use a compact constructor for validation.
Records are only shallowly immutable, so copy mutable components like lists.
A common interview question is: "What is the difference between a record and a normal class?" Answer: a record is final, immutable, cannot extend other classes, cannot declare extra instance fields, and automatically gets value-based equals(), hashCode(), toString(), and accessors.