Introduction
Modern Java development focuses on writing code that is clean, concise, and easy to maintain. Before Java Records were introduced, developers often had to write repetitive boilerplate code for classes whose primary purpose was to hold data. These classes, commonly known as POJOs (Plain Old Java Objects) or DTOs (Data Transfer Objects), required constructors, getter methods, equals(), hashCode(), and toString() methods even though they contained very little business logic.
To solve this problem, Java introduced Records as a preview feature in Java 14, followed by a second preview in Java 15, and officially made them a standard feature in Java 16. Since Java 17 is a Long-Term Support (LTS) release.
Records provide a compact syntax for declaring immutable data classes while automatically generating much of the repetitive code developers previously had to write manually.
What are Java Records?
A Java Record is a special type of class designed to store immutable data. It automatically generates many commonly used methods, reducing boilerplate code and making applications easier to read and maintain.
When you create a record, Java automatically generates:
- Private final fields
- A canonical constructor
- Public accessor methods
- equals()
- hashCode()
- toString()
Records are ideal for objects that primarily represent data rather than behavior.
Why Were Records Introduced?
Before Records, developers had to write repetitive code like this:
public class Student {
private final int id;
private final String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
@Override
public boolean equals(Object obj) {
// implementation
return true;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
With Records, the same class becomes:
public record Student(int id, String name) {}
This single line automatically creates everything required.
Syntax of Java Records
public record RecordName(DataType field1,
DataType field2,
DataType field3) {
}
Example
public record Employee(
int id,
String name,
double salary
) {}
Creating Your First Record
public record Student(int id, String name) {}
Using the record:
public static void main(String[] args) {
Student student = new Student(101, "Rahul");
System.out.println(student.id());
System.out.println(student.name());
System.out.println(student);
}
}
Output
Rahul
Student[id=101, name=Rahul]
Notice that the accessor methods are named:
student.id()
student.name()
instead of
getId()
getName()
Features of Java Records
1. Less Boilerplate Code
Records automatically generate constructors, getters, equals(), hashCode(), and toString().
3. Automatic Constructor
Product product = new Product(1, "Laptop");
The constructor is generated automatically.
4. Auto-generated Accessors
System.out.println(product.id());
System.out.println(product.name());
5. Auto-generated equals()
Product p1 = new Product(1, "Laptop");
Product p2 = new Product(1, "Laptop");
System.out.println(p1.equals(p2));
Output:
6. Auto-generated hashCode()
Useful when storing objects in collections like HashMap and HashSet.
7. Auto-generated toString()
System.out.println(product);
Output
Compact Constructor
Records allow validation using a compact constructor.
public record Employee(int id, String name, double salary) {
public Employee {
if (salary < 0) {
throw new IllegalArgumentException("Salary cannot be negative.");
}
}
}
Usage
Employee emp = new Employee(1, "Amit", 50000);
Custom Methods in Records
Records can contain business methods.
public record Rectangle(double length, double width) {
public double area() {
return length * width;
}
}
Usage
Rectangle rectangle = new Rectangle(10, 5);
System.out.println(rectangle.area());
Output
Static Members in Records
Records can also contain static fields and methods.
public record Circle(double radius) {
public static final double PI = 3.14159;
public double area() {
return PI * radius * radius;
}
}
Nested Records
Records can be declared inside another class.
public class Company {
public record Employee(int id, String name) {}
}
Usage
Company.Employee employee =
new Company.Employee(101, "John")
Real-Life Example
Suppose you’re developing an online shopping application.
Instead of creating a lengthy Product class:
public class Product {
private final int id;
private final String name;
private final double price;
// Constructor
// Getters
// equals()
// hashCode()
// toString()
}
You can simply write:
public record Product(
int id,
String name,
double price
) {}
Usage
Product laptop =
new Product(101, "Laptop", 65000);
System.out.println(laptop);
Output
This makes DTOs much cleaner.
Records with Collections
import java.util.List;
public record Student(
int id,
String name,
List subjects
) {}
Usage
Student student =
new Student(
1,
"Aman",
List.of("Java", "Spring", "SQL")
);
System.out.println(student);
Although the reference is immutable, the collection itself should be made unmodifiable if complete immutability is required.
Records vs Traditional Classes
| Feature | Record | Traditional Class |
|---|---|---|
| Boilerplate Code | Very Low | High |
| Constructor | Auto-generated | Manual |
| Getters | Auto-generated | Manual |
| equals() | Auto-generated | Manual |
| hashCode() | Auto-generated | Manual |
| toString() | Auto-generated | Manual |
| Mutable Fields | No | Yes |
| Inheritance | Cannot extend classes | Supported |
| Best For | Data Models | Business Logic |
Advantages of Java Records
- Less code to write
- Improved readability
- Immutable by default
- Built-in constructor
- Built-in accessors
- Better maintainability
- Perfect for DTOs
- Better support for modern Java development
- Safer data representation
- Easier debugging through auto-generated toString()
Limitations of Records
Records are not suitable in every situation.
1. Cannot Extend Another Class
record Student(int id) extends Person {}
This is not allowed.
2. Cannot Add Instance Fields
public record Student(int id) {
private String city; // Error
}
Only record components define the instance state.
3. Immutable State
You cannot modify fields after object creation.
4. Not Suitable for Rich Domain Models
If your class contains extensive business logic and mutable state, a regular class is usually a better choice.
Common Mistakes
Using Getter Naming Convention
Wrong
student.getName();
Correct
student.name();
Trying to Modify Fields
Wrong
student.name = "Rahul";
Fields are immutable.
Using Records for Mutable Objects
Records should represent data, not changing state.
Forgetting Validation
Use compact constructors to validate inputs.
public Employee {
if (salary < 0)
throw new IllegalArgumentException();
}
Best Practices
- Use records for DTOs.
- Keep records immutable.
- Validate data using compact constructors.
- Avoid placing heavy business logic inside records.
- Use descriptive component names.
- Prefer records when objects mainly transport data.
Conclusion
Java Records are one of the most valuable language features in modern Java (17–21). They significantly reduce boilerplate code while promoting immutability, readability, and maintainability. By automatically generating constructors, accessor methods, equals(), hashCode(), and toString(), Records let developers focus on application logic instead of repetitive code.
Records are especially useful for data-centric classes such as DTOs, API payloads, configuration objects, and value objects. While they are not a replacement for every traditional class—particularly those requiring mutable state or complex inheritance—they are an excellent choice whenever the primary purpose of a class is to represent immutable data.