← Back to Chapters

Java Records

? Java Records

? Quick Overview

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().

? Key Concepts

  • Records are immutable by default
  • All fields are private final
  • Used mainly for data transfer objects (DTOs)
  • Records cannot extend other classes
  • They implicitly extend java.lang.Record

? Syntax & Theory

A record declaration looks similar to a class but focuses only on the data it holds. The parameters inside the parentheses define the record components.

? View Code Example
// Defining a simple record with two fields
public record Student(int id, String name) {
}

? Code Example

? View Code Example
// 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());
}
}

? Live Output / Explanation

When the program runs, the record automatically provides accessor methods. Calling s.id() and s.name() returns the stored values.

Output:
101
Amit

? Interactive Playground

Step 1: Define your Record data.

Student s = new Student( , );

Step 2: Call generated methods on object s.

Java Console // Waiting for instantiation...

✅ Tips & Best Practices

  • Use records only for immutable data
  • Prefer records for DTOs and API responses
  • Avoid adding complex logic inside records
  • Keep records small and focused

? Try It Yourself

  • Create a Book record with title and price
  • Print the record using toString()
  • Compare two record objects using equals()