Java Use a Record for a Small Data Carrier
A record gives a transparent data carrier component accessors and generated value-oriented methods. It reduces routine code, but does not make every referenced component deeply immutable.
Understand the idea
A record declaration names its components. The compiler supplies a canonical constructor, accessors, equals, hashCode and toString, subject to the language rules. A compact constructor can validate or normalise the incoming component values. A record is final and cannot extend an arbitrary application class. If a component is a mutable list, make a defensive copy when the record’s contract should not expose future changes.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.List;
public class Main {
record Booking(String session, List<String> names) {
Booking {
if (session == null || session.isBlank()) throw new IllegalArgumentException("session required");
names = List.copyOf(names);
}
}
public static void main(String[] args) {
Booking booking = new Booking("Woodwork", List.of("Asha", "Noor"));
System.out.println(booking.session());
System.out.println(booking.names().size());
}
}
Expected output
Woodwork
2The compact constructor checks the session and copies the names into an unmodifiable list. The generated names accessor then returns that protected list reference. List.copyOf also rejects null elements, which is a deliberate contract here rather than an incidental implementation detail. Records have been a final language feature since Java 16 and are available in this course baseline.
Check the official Java documentation for detailed contracts and supported options.