Java Snippet

Java Record for Lightweight DTOs

Difficulty: Easy

Records (Java 14 preview, stable since Java 16) collapse boilerplate immutable data carriers into one line. This snippet shows the canonical record, a compact constructor for validation, and using records as map keys. The runnable code targets Java 13 syntax (since the test runner is OpenJDK 13), with the modern record equivalent shown inline in comments and explanations.

Code Snippets
/

Java Record for Lightweight DTOs

Java Record for Lightweight DTOs

Records (Java 14 preview, stable since Java 16) collapse boilerplate immutable data carriers into one line. This snippet shows the canonical record, a compact constructor for validation, and using records as map keys. The runnable code targets Java 13 syntax (since the test runner is OpenJDK 13), with the modern record equivalent shown inline in comments and explanations.

Java
Easy
3 snippets
java-records
data-structures
implementation

809 views

6

This is the long-hand form of record Point(int x, int y) {}. The record declaration auto-generates exactly these members: a canonical constructor, accessor methods named after each component (x(), y()), and value-based equals, hashCode, and toString. Records are implicitly final and their components are final, so instances are immutable and safe to share across threads. Use them for DTOs, pair returns, and value objects, but reach for a regular class when you need mutability or inheritance.