CKTIS / Java
The keyword record
The keyword record: A record declaration creates a nominal data class whose components determine private final fields, accessors, and a canonical constructor.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
recordA record declaration creates a nominal data class whose components determine private final fields, accessors, and a canonical constructor.
Use a record for transparent values; write its compact canonical constructor as Name { ... } to validate or normalize parameters before automatic field assignment.
A compact canonical constructor has no parameter list and cannot explicitly assign component fields; shallow finality does not freeze mutable component objects.
A record is implicitly final and extends java.lang.Record; custom accessors or equals must preserve its declared invariant and value semantics.
The compact canonical constructor creates Range[start=2, end=7], size=5, and components=2; a reversed range gives invalid=reversed.
Examples
public class Main { record Range(int start,int end){ Range { if(start>end)throw new IllegalArgumentException("reversed"); } int size(){return end-start;} } public static void main(String[] a){var r=new Range(2,7);System.out.println(r);System.out.println("size="+r.size());System.out.println("components="+Range.class.getRecordComponents().length);try{new Range(5,1);}catch(IllegalArgumentException e){System.out.println("invalid="+e.getMessage());}} }Result
Range[start=2, end=7] size=5 components=2 invalid=reversed
The compact canonical constructor creates Range[start=2, end=7], size=5, and components=2; a reversed range gives invalid=reversed.