Introduction
Java 14, released in March 2020, introduced records as a preview language feature under JEP 359, and finalised them in Java 16 under JEP 395. A record is a special kind of class whose purpose is to hold immutable data: the developer declares the components (the fields) in the header, and the compiler generates the constructor, accessor methods, equals, hashCode, and toString automatically. Before records, writing a value-like class in Java meant writing four boilerplate methods by hand or generating them with an IDE wizard or a library like Lombok. Java 14 records eliminate that boilerplate at the language level, with the additional guarantee that the resulting class is shallowly immutable.
For a Java learner, java 14 records is the gateway to writing clean value classes in modern Java. Records are the natural data-carrier pairing for switch expressions (Java 14) and pattern matching (Java 16, Java 21). This post walks through the record declaration, the implicitly generated methods, the compact constructor for validation, and the rules that distinguish records from regular classes.
What is Java 14 Records?
A record is declared with the keyword record, followed by a name, a parenthesised list of components (typed name pairs), and a body. For example, public record Point(int x, int y) {} declares a record named Point with two int components x and y. The compiler generates a canonical constructor Point(int x, int y) that assigns the arguments to private final fields of the same names; accessor methods int x() and int y() that return the field values; an equals method that compares components field-by-field; a hashCode method consistent with equals; and a toString method that includes the record name and every component value.
Conceptually, records belong to the family of nominal data-carrier types, similar to Kotlin's data classes, Scala's case classes, and C#'s record types. Unlike regular Java classes, records have three restrictions: they are implicitly final (cannot be extended), their fields are implicitly final (cannot be reassigned after construction), and they cannot have an extends clause (they implicitly extend java.lang.Record). Records can still implement interfaces, declare static fields and methods, and declare instance methods, but they cannot declare additional instance fields beyond the components.
How Java 14 Records Works - Step by Step
Step 1: Declare the record header. The header lists the components as a parenthesised comma-separated list of (type name) pairs. The order of components is significant: it determines the parameter order of the canonical constructor and the field declaration order.
Step 2: Let the compiler generate the canonical constructor. The implicit constructor has the same parameter list as the header, in the same order. It assigns each parameter to a private final field of the same name. No explicit constructor body is generated unless you write a compact constructor.
Step 3: Let the compiler generate accessors. For each component, an accessor method with the same name as the component (not getX) is generated. The accessor returns the field value. For a record Point(int x, int y), the accessors are int x() and int y().
Step 4: Add a compact constructor for validation. If you want to validate the components before assigning them, write a constructor whose signature omits the parameter list and whose body ends with implicit assignment. For example, public record Range(int lo, int hi) { public Range { if (lo > hi) throw new IllegalArgumentException(lo + " > " + hi); } } validates that lo is not greater than hi. The body runs before the implicit assignment, so you can reassign the parameters (this.lo = Math.max(lo, 0);) to normalise them.
Step 5: Use equals and hashCode as expected. Two record instances are equal if and only if they have the same record type and all corresponding components are equal. The hashCode is computed from all component hashCodes, so equal records always have the same hash.
Java Program for Records
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class RecordDemo {
// (1) Minimal record
public record Point(int x, int y) {}
// (2) Record with compact constructor for validation
public record Range(int lo, int hi) {
public Range {
if (lo > hi) {
throw new IllegalArgumentException(
"lo " + lo + " > hi " + hi);
}
}
}
// (3) Record implementing an interface
public interface Shape { double area(); }
public record Circle(double r) implements Shape {
@Override
public double area() { return Math.PI * r * r; }
}
public record Square(double side) implements Shape {
@Override
public double area() { return side * side; }
}
// (4) Record with extra methods and static factories
public record Money(long cents, String currency) {
public static Money usd(long cents) { return new Money(cents, "USD"); }
public static Money eur(long cents) { return new Money(cents, "EUR"); }
public Money plus(Money other) {
Objects.requireNonNull(other, "other");
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException(
"currency mismatch: " + currency + " vs " + other.currency);
}
return new Money(cents + other.cents, currency);
}
}
// (5) Record with normalised compact constructor
public record Email(String local, String domain) {
public Email {
local = local == null ? "" : local.trim().toLowerCase();
domain = domain == null ? "" : domain.trim().toLowerCase();
}
}
public static void main(String[] args) {
// (1) Point: accessors are x() and y()
Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
Point p3 = new Point(4, 5);
System.out.println("(1) p1: " + p1);
System.out.println("(1) p1.x(): " + p1.x() + ", p1.y(): " + p1.y());
System.out.println("(1) p1.equals(p2): " + p1.equals(p2));
System.out.println("(1) p1.equals(p3): " + p1.equals(p3));
System.out.println("(1) p1.hashCode() == p2.hashCode(): "
+ (p1.hashCode() == p2.hashCode()));
// (2) Range: compact constructor rejects lo > hi
System.out.println("(2) Range(1, 5): " + new Range(1, 5));
try {
new Range(5, 1);
} catch (IllegalArgumentException e) {
System.out.println("(2) threw: " + e.getMessage());
}
// (3) Shapes via interface
List<Shape> shapes = List.of(
new Circle(2.0), new Square(3.0), new Circle(1.0));
double total = 0;
for (Shape s : shapes) total += s.area();
System.out.println("(3) total area: " + total);
// (4) Money: static factories and instance method
Money a = Money.usd(500);
Money b = Money.usd(300);
System.out.println("(4) a.plus(b): " + a.plus(b));
try {
Money.eur(100).plus(Money.usd(200));
} catch (IllegalArgumentException e) {
System.out.println("(4) threw: " + e.getMessage());
}
// (5) Email: normalisation in compact constructor
Email e1 = new Email(" Alice ", "Example.COM");
Email e2 = new Email("alice", "example.com");
System.out.println("(5) e1: " + e1);
System.out.println("(5) e2: " + e2);
System.out.println("(5) e1.equals(e2): " + e1.equals(e2));
// (6) Record in Map key
Map<Point, String> grid = Map.of(
new Point(0, 0), "origin",
new Point(1, 0), "east",
new Point(0, 1), "north");
System.out.println("(6) grid.get((0,1)): "
+ grid.get(new Point(0, 1)));
System.out.println("(6) grid.get((2,2)): "
+ grid.get(new Point(2, 2)));
// (7) Reflection-free type check
Object o = new Point(7, 8);
if (o instanceof Point pp) {
System.out.println("(7) o is Point(" + pp.x() + ", " + pp.y() + ")");
}
}
}
Code Explanation - Line by Line
Record (1) Point is the simplest possible record: two int components, no body. The compiler generates everything else: the canonical constructor, the x() and y() accessors, equals, hashCode, and toString. The println output (1) shows that toString formats as "Point[x=3, y=4]" automatically.
Record (2) Range adds a compact constructor. The compact constructor has no parameter list (the header already declares the parameters); its body runs before the implicit assignment of parameters to fields. The body throws IllegalArgumentException if lo is greater than hi, ensuring that no Range instance can ever represent an invalid range. Because the parameters lo and hi are implicit final assignments, you cannot write to this.lo directly in the compact constructor; instead you reassign the parameter lo, which the compiler then writes to the field.
Record (3) Circle and Square implement the Shape interface. A record can implement any number of interfaces but cannot extend a class (other than java.lang.Record, which it extends implicitly). The @Override annotation on the area method is optional but recommended for clarity. The List.of factory creates an immutable list of the two shapes and one circle, and the for loop sums their areas polymorphically through the Shape interface.
Record (4) Money shows how to combine static factories with instance methods on a record. The static factories usd and eur are convenient constructors that fix the currency argument. The plus instance method returns a new Money instance (records are immutable, so addition produces a new value rather than mutating). The Objects.requireNonNull call and the currency mismatch check demonstrate that you can add arbitrary validation logic to a record's instance methods.
Record (5) Email demonstrates field normalisation in the compact constructor. By reassigning the parameters local and domain to their trimmed lowercase forms, the constructor ensures that every Email instance stores a normalised form. The output (5) shows that two Email instances constructed from " Alice "@Example.COM" and "alice@example.com" are equal, because the normalisation in the compact constructor produces identical field values for both.
Section (6) uses a Point record as a Map key. Because the compiler generates equals and hashCode based on the components, two Point instances with the same x and y are equal and have the same hash, so the Map lookup works correctly. This is the most common use case for records: as keys in hash-based collections.
Section (7) shows the Java 16 pattern matching for instanceof, which combines naturally with records. The instanceof Point pp pattern binds pp to a variable of type Point, after which the x() and y() accessors can be called directly without an explicit cast.
Sample Input and Output
Input: args = [] (uses fixed demo data) Output: (1) p1: Point[x=3, y=4] (1) p1.x(): 3, p1.y(): 4 (1) p1.equals(p2): true (1) p1.equals(p3): false (1) p1.hashCode() == p2.hashCode(): true (2) Range(1, 5): Range[lo=1, hi=5] (2) threw: lo 5 > hi 1 (3) total area: 24.707963267948966 (4) a.plus(b): Money[cents=800, currency=USD] (4) threw: currency mismatch: EUR vs USD (5) e1: Email[local=alice, domain=example.com] (5) e2: Email[local=alice, domain=example.com] (5) e1.equals(e2): true (6) grid.get((0,1)): north (6) grid.get((2,2)): null (7) o is Point(7, 8)
The output confirms that the generated toString includes the record name and component values, that equals compares component values, that the compact constructor validates Range, that interface implementation works, that field normalisation in Email makes two differently-formatted inputs equal, and that records work as Map keys. Section (3) total area is Math.PI times 2 squared (Circle r=2) plus 3 squared (Square side=3) plus Math.PI times 1 squared (Circle r=1), which equals 4 PI plus 9 plus PI equals 5 PI plus 9, approximately 24.708.
Common Mistakes to Avoid
The first mistake is declaring extra instance fields in a record body. The Java Language Specification forbids instance fields outside the header because they would break the auto-generated equals and hashCode contract: a record with an extra field would have to override equals to include the field, defeating the purpose of the auto-generated methods. If you need extra derived state, compute it in a method on demand or store it in a static cache.
The second mistake is using the assignment-to-this form in a compact constructor. The compact constructor runs before the implicit assignment of parameters to fields, so writing this.x = x is illegal: the field x does not yet exist when the compact constructor body runs. To normalise a parameter, reassign the parameter itself (x = Math.max(x, 0);) and the compiler then assigns the normalised value to the field.
The third mistake is adding setters to a record. Records are immutable by design: the components are final and the canonical constructor runs only once. Adding a public void setX(int x) method that does nothing (because the field is final) is misleading and confusing. If you need a mutable version, use a regular class with public fields and explicit equals and hashCode, not a record with sham setters.
The fourth mistake is treating record components as JavaBean properties. Record components are accessed via methods named exactly like the component (e.g., x() for the x component), not via getX() and setX() methods as the JavaBean convention would dictate. Calling getR() on a Circle record fails to compile; the correct call is r(). The accessor naming matters when integrating with frameworks that expect JavaBean-style introspection.
Real-World Applications
In production Java code, records are heavily used in domain modelling, event sourcing, and DTO (data transfer object) representation. Spring Framework 6+ supports records as @ConfigurationProperties binding targets, as @RequestMapping method parameters, and as @RestController return types. The Jackson JSON library supports records for deserialisation in version 2.12+, replacing the older constructor-only binding that required reflection workarounds.
In build tooling, the Gradle build tool uses records for task configuration types like TaskExecutionRequest and ProviderConvertible. The Maven build tool's plugin descriptor uses records for parameter binding metadata. Both frameworks report that records dramatically reduce the boilerplate of model classes that previously required Lombok annotations or IDE-generated equals and hashCode methods.
In testing libraries, JUnit 5's TestDescriptor and TestSource interfaces use records for value subclasses. The AssertJ assertion library uses records internally for its precondition and assertion error representations. The Mockito framework uses records for invocation metadata, where the immutability of the record guarantees that the recorded invocation cannot be tampered with after the fact.
In compiler and parser code, the JavaParser library uses records for AST node types in its modern API. The Eclipse JDT compiler uses records for binding metadata. The IntelliJ IDEA PSI tree uses records for the closed set of immutable metadata carriers. The exhaustive equals and hashCode contract provided by records ensures that two AST nodes with the same components are interchangeable, simplifying visitor caching.
Conclusion
Java 14 records (finalised in Java 16) eliminate the boilerplate of immutable data-carrier classes by generating the canonical constructor, accessors, equals, hashCode, and toString from a single line of header declaration. The compact constructor enables validation and normalisation, and the implicit immutability makes records the natural data-carrier pairing for switch expressions and pattern matching. Next, study Java 14 pattern matching for instanceof to see how the cast-and-bind boilerplate is similarly eliminated, and then read up on Java 16 record patterns to see how pattern matching destructures records by their components.
Comments
Comments
Post a Comment