What is Record in Java: Simple Explanation and Example
record is a special kind of class designed to hold immutable data with less code. It automatically provides methods like equals(), hashCode(), and toString() based on its fields.How It Works
A record in Java is like a simple container for data, similar to a form you fill out with fixed fields. Instead of writing all the usual code for storing data, comparing objects, or printing them, Java creates that code for you automatically.
Think of a record as a ready-made box with labeled compartments. You just say what labels (fields) you want, and Java builds the box with all the tools to use it properly. This makes your code shorter and easier to read.
Example
This example shows how to define a record for a person with a name and age, and how to use it.
public record Person(String name, int age) { } public class Main { public static void main(String[] args) { Person p = new Person("Alice", 30); System.out.println(p.name()); // Access name System.out.println(p.age()); // Access age System.out.println(p); // Uses auto-generated toString() } }
When to Use
Use records when you need simple, immutable data carriers without extra behavior. They are perfect for storing data like coordinates, user info, or configuration settings where you want to avoid writing repetitive code.
Records are great in real-world cases such as returning multiple values from a method, transferring data between parts of a program, or representing fixed data structures in APIs.
Key Points
- Records are immutable data classes introduced in Java 16.
- They automatically generate constructor, getters,
equals(),hashCode(), andtoString(). - Records reduce boilerplate code for simple data holders.
- Fields in records are final and cannot be changed after creation.