What is a record in Java, and its usage?

A record is a special type of class introduced in Java to simplify the creation of immutable data carrier objects. It automatically generates common methods such as constructors, getters, equals(), hashCode(), and toString(), significantly reducing boilerplate code. Records are ideal when the primary purpose of a class is to store and transfer data.

Key Points: • Records provide a concise way to create immutable data models with minimal code. • The compiler automatically generates accessor methods, constructor, equals(), hashCode(), and toString(). • Records are commonly used for DTOs (Data Transfer Objects), API responses, configuration objects, and value-based classes.

Example: In a REST API, instead of writing a full Employee DTO class with fields, constructor, getters, equals(), hashCode(), and toString(), a record can represent the same data in a single line, making the code cleaner and easier to maintain.

Code Example:

public record Employee(int id, String name, double salary) {
}

public class Main {

    public static void main(String[] args) {

        Employee emp = new Employee(101, "John", 50000);

        System.out.println(emp.id());
        System.out.println(emp.name());
        System.out.println(emp);
    }
}

Interview Tip: A concise interview answer is: A record is a lightweight, immutable data carrier class introduced in Java. It automatically generates constructors, accessor methods, equals(), hashCode(), and toString(), reducing boilerplate code and making it ideal for DTOs and value objects.