Java Records are a special type of class introduced to reduce boilerplate code. They are designed to represent immutable data carriers with minimal syntax. Records automatically provide constructors, getters, equals(), hashCode(), and toString().
private finaljava.lang.RecordA record declaration looks similar to a class but focuses only on the data it holds. The parameters inside the parentheses define the record components.
// Defining a simple record with two fields
public record Student(int id, String name) {
}
// Using a Java record to store and access data
public class Main {
public static void main(String[] args) {
Student s = new Student(101, "Amit");
System.out.println(s.id());
System.out.println(s.name());
}
}
When the program runs, the record automatically provides accessor methods. Calling s.id() and s.name() returns the stored values.
Output:
101
Amit
Step 1: Define your Record data.
Step 2: Call generated methods on object s.
Book record with title and pricetoString()equals()