Repaso
Español
Java CoreIntermediateJV-21

What do records (Java 16+) give you with record Point(int x, int y) {}?

Options

  1. A mutable class with setters for each component field
  2. An immutable class with getters, equals and toString (Correct option)
  3. A database table that is mapped from the components
  4. A class that is not allowed to declare any methods

Answer

An immutable data class with constructor, getters (x()), equals, hashCode and toString generated automatically

Why

A record is a short way to declare a plain data carrier. The compiler generates the constructor, accessors (p.x(), not getX()), equals, hashCode and toString from the listed components.

Fields are final, so records are immutable. They are ideal for DTOs, API responses and map keys. Records can still have extra methods and validation in a compact constructor.

Remember

record = immutable data class with boilerplate generated.

Key terms

Practice this question in Repaso