Sobes.tech
Junior — Middle

What is the role and application of records in the Java language?

sobes.tech AI

Answer from AI

In Java, records are a special type of class designed for storing immutable data. They were introduced to simplify the creation of classes that mainly contain fields and automatically provide methods for accessing them, as well as methods like equals(), hashCode(), and toString().

Main features of records:

  • Fields are final and private by default.
  • Constructors, getters, equals(), hashCode(), and toString() are automatically generated.
  • Records are inherently immutable.

Example of a record:

public record Point(int x, int y) {}

// Usage:
Point p = new Point(10, 20);
System.out.println(p.x()); // 10
System.out.println(p); // Point[x=10, y=20]

Records are convenient for creating DTOs (Data Transfer Objects), keys in collections, and other cases where a simple data container is needed without additional logic.