Java Records

A record (Java 16+) is a short way to write a class which only carries data. With one line you get the fields, the constructor, the getters, equals(), hashCode() and toString().

A record in one line

record Student(String name, int marks) { }

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya", 88);
        System.out.println(s);                    // toString made for you
        System.out.println(s.name());             // the getter has the field name
        System.out.println(s.marks());

        Student same = new Student("Riya", 88);
        System.out.println(s.equals(same));       // compares the values
        System.out.println(s == same);            // different objects
    }
}
Output

Student[name=Riya, marks=88]
Riya
88
true
false

The same class in the old way needs about 30 lines of code. A record is immutable: the fields are final and have no setters.

Validation: compact constructor

record Age(int value) {
    Age {                                           // compact constructor, no parameters
        if (value < 0 || value > 120) {
            throw new IllegalArgumentException("Invalid age: " + value);
        }
    }
}

public class Valid {
    public static void main(String[] args) {
        System.out.println(new Age(25));
        try {
            new Age(-1);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Output

Age[value=25]
Error: Invalid age: -1

Extra methods and static members

record Rectangle(double width, double height) {
    double area() {
        return width * height;
    }

    static Rectangle square(double side) {
        return new Rectangle(side, side);
    }
}

public class Extra {
    public static void main(String[] args) {
        System.out.println(new Rectangle(3, 4).area());
        System.out.println(Rectangle.square(5));
    }
}
Output

12.0
Rectangle[width=5.0, height=5.0]

Records and lists

import java.util.List;

record Product(String name, double price) { }

public class Lists {
    public static void main(String[] args) {
        List<Product> items = List.of(new Product("Pen", 10), new Product("Book", 250), new Product("Bag", 900));
        double total = 0;
        for (Product p : items) {
            total += p.price();
        }
        System.out.println("Total: " + total);
        System.out.println(items.get(1));
    }
}
Output

Total: 1160.0
Product[name=Book, price=250.0]

Rules

  • A record can implement interfaces, but can not extend a class.
  • You can not add instance fields outside the header.
  • Use a record for DTOs, API responses, keys of maps and small value objects.
  • Use a normal class when the object must change (mutable) or has a complex behavior.
Note: Records are also great together with pattern matching and sealed types. See Pattern Matching and Sealed Classes. Next: Java Packages and Imports.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.