Record constructors: compact, canonical and extra
A record writes its constructor for you, but every record still lets you run code at construction time. The compact constructor is where you validate, normalize and copy the incoming values, and every way of creating the record goes through it. This page explains how the generated constructor is assembled, shows each form running, and shows the rules and copy mistakes that catch people out.
Contents
How a record is constructed Validating, normalizing and copying in a compact constructor Normalizing so that equal values are equal records Explicit canonical constructor, extra constructors and factories What the compiler rejects Defensive copy traps Immutable updates: with-methods Choosing where to put the code
How a record is constructed
Every record has exactly one canonical constructor: the one whose parameters match the components in name, type and order. If you do not write it, the compiler generates one that assigns each parameter to its field. If you do write it, you can choose between two forms, and you can add further constructors that delegate to it.
The key to the compact form is when the fields are assigned. In record Range(int min, int max) { Range { ... } }minmaxthis.min = min; this.max = max;
Because every path leads through the canonical constructor, a check written there runs for newthis(...)
| Form | Syntax | Fields assigned | Best for |
|---|---|---|---|
| Compact canonical constructor | Range { ... } | Automatically, after the body | Validation, normalization, defensive copies |
| Explicit canonical constructor | Range(int min, int max) { ... } | By hand, every field | Code that needs this.x |
| Additional constructor | Range() { this(0, 0); } | Through this(...) | Defaults (a named factory is often clearer) |
| Static factory | static Range of(int a, int b) | Through the canonical constructor | Alternative inputs with a descriptive name |
| With-method | Range withMax(int m) | Through the canonical constructor | A copy with one component changed |
All of these arrived with records in Java 16 (JEP 395), after previews in Java 14 and 15. Every example on this page is a complete program, and its output below comes from running it on JDK 21. For what records generate besides the constructor, see
Validating, normalizing and copying in a compact constructor
The program has one record for each of the three jobs. The name " Alice "
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class CompactConstructor {
record Range(int min, int max) {
Range { // no parameter list: compact form
if (min > max) {
throw new IllegalArgumentException("min " + min + " > max " + max);
}
} // this.min = min; this.max = max; added here
}
record Person(String name, int age) {
Person {
Objects.requireNonNull(name, "name");
name = name.strip(); // reassigning the parameter changes the field
if (age < 0) {
throw new IllegalArgumentException("age " + age);
}
}
}
record Team(String name, List<String> members) {
Team {
members = List.copyOf(members); // defensive, unmodifiable copy
}
}
public static void main(String[] args) {
System.out.println(new Range(1, 5));
try {
new Range(5, 1);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
Person p = new Person(" Alice ", 30);
System.out.println("name stored as [" + p.name() + "]");
try {
new Person(null, 30);
} catch (NullPointerException e) {
System.out.println("rejected null: " + e.getMessage());
}
List<String> names = new ArrayList<>(List.of("Ana", "Ben"));
Team t = new Team("core", names);
names.add("Cho");
System.out.println("caller changed its list, team still: " + t.members());
try {
t.members().add("Dev");
} catch (UnsupportedOperationException e) {
System.out.println("members() cannot be modified: UnsupportedOperationException");
}
}
}
Output:
Range[min=1, max=5]
rejected: min 5 > max 1
name stored as [Alice]
rejected null: name
caller changed its list, team still: [Ana, Ben]
members() cannot be modified: UnsupportedOperationException
was rejected with the message built in the constructor. Range 1 to 5 was accepted unchanged.new Range(5, 1)- The brackets show that only
was stored. The body reassigned theAlice parameter, and the automatic assignment at the end copied that new value into the field.name produced the messageObjects.requireNonNull(name, "name") . Without it, the call toname would have thrown a less helpfulstrip() one line later.NullPointerException- The caller added "Cho" to its own list, but the team still holds
, and[Ana, Ben] throwsmembers().add .UnsupportedOperationException made a private, unmodifiable copy, so the record is now deeply immutable as long as the elements are.List.copyOf
Normalizing so that equal values are equal records
The generated equals
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
public class Normalize {
// Stores every fraction in lowest terms with a positive denominator,
// so equal values are equal records
record Fraction(long num, long den) implements Comparable<Fraction> {
Fraction {
if (den == 0) {
throw new ArithmeticException("denominator is zero");
}
long g = gcd(Math.abs(num), Math.abs(den));
long sign = den < 0 ? -1 : 1;
num = sign * num / g;
den = sign * den / g;
}
static long gcd(long a, long b) {
return b == 0 ? Math.max(a, 1) : gcd(b, a % b);
}
Fraction plus(Fraction o) {
return new Fraction(num * o.den + o.num * den, den * o.den);
}
@Override
public int compareTo(Fraction o) {
return Long.compare(num * o.den, o.num * den);
}
}
record Email(String address) {
Email {
address = address.strip().toLowerCase(Locale.ROOT);
if (address.indexOf('@') < 1) {
throw new IllegalArgumentException("not an email: " + address);
}
}
}
public static void main(String[] args) {
System.out.println("2/4 -> " + new Fraction(2, 4));
System.out.println("3/-6 -> " + new Fraction(3, -6));
System.out.println("0/5 -> " + new Fraction(0, 5));
System.out.println("1/6 + 1/3 = " + new Fraction(1, 6).plus(new Fraction(1, 3)));
System.out.println("2/4 equals 1/2: " + new Fraction(2, 4).equals(new Fraction(1, 2)));
Set<Fraction> set = new TreeSet<>(List.of(
new Fraction(1, 2), new Fraction(2, 4), new Fraction(-1, 3), new Fraction(5, 10)));
System.out.println("distinct fractions: " + set);
Set<Email> emails = Set.of(new Email(" Ana@Example.com"));
System.out.println("contains ana@example.com: "
+ emails.contains(new Email("ana@example.com")));
}
}
Output:
2/4 -> Fraction[num=1, den=2]
3/-6 -> Fraction[num=-1, den=2]
0/5 -> Fraction[num=0, den=1]
1/6 + 1/3 = Fraction[num=1, den=2]
2/4 equals 1/2: true
distinct fractions: [Fraction[num=-1, den=3], Fraction[num=1, den=2]]
contains ana@example.com: true
- 2/4 is stored as 1/2 and 3/-6 as -1/2: the constructor divides by the greatest common divisor and moves the sign into the numerator. 0/5 becomes 0/1, because
returns 5 for (0, 5).gcd - 1/6 + 1/3 is computed as 9/18 and normalized to 1/2 by the same constructor, since
callsplus .new - Four fractions went into the
but only two remain, because 1/2, 2/4 and 5/10 became identical records.TreeSet - The email typed as
was found by" Ana@Example.com" .ana@example.com keeps the lower-casing independent of the machine's language settings (in a Turkish locale,Locale.ROOT is a dotless i)."I".toLowerCase()
An earlier version of this program built the set with Set.of(...)IllegalArgumentException: duplicate element: Fraction[num=1, den=2]Set.of
Explicit canonical constructor, extra constructors and factories
The full form repeats the parameter list and must assign every field itself. The program rounds a temperature to one decimal place: 36.666 shows the rounding to 36.7, and 212 °F should convert to exactly 100 °C and back.
public class OtherConstructors {
record Temperature(double celsius) {
// Explicit canonical constructor: same parameters as the components,
// and every field must be assigned by hand
Temperature(double celsius) {
if (celsius < -273.15) {
throw new IllegalArgumentException("below absolute zero: " + celsius);
}
this.celsius = Math.round(celsius * 10) / 10.0;
}
// Any other constructor must start by calling another constructor
Temperature() {
this(20.0);
}
static Temperature ofFahrenheit(double f) {
return new Temperature((f - 32) * 5 / 9);
}
// An accessor can be overridden, but it must be public and return the component type
@Override
public double celsius() {
return celsius;
}
double fahrenheit() {
return celsius * 9 / 5 + 32;
}
}
public static void main(String[] args) {
System.out.println("default: " + new Temperature());
System.out.println("rounded: " + new Temperature(36.666));
Temperature boiling = Temperature.ofFahrenheit(212);
System.out.println("from 212 F: " + boiling + ", back to F: " + boiling.fahrenheit());
try {
new Temperature(-300);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
Output:
default: Temperature[celsius=20.0]
rounded: Temperature[celsius=36.7]
from 212 F: Temperature[celsius=100.0], back to F: 212.0
rejected: below absolute zero: -300.0
- The no-argument constructor produced 20.0 by calling
, so the absolute-zero check also covers defaults.this(20.0) computed (212 - 32) × 5 / 9 = 100.0. A static factory has a name, which makes it clearer than a second constructor taking aofFahrenheit(212) :double could not say which scale it means.new Temperature(212)- -300 is below -273.15 and was rejected with the value in the message.
- The overridden accessor
just returns the field, to show the rules: it must becelsius() , return the component's type, take no parameters and declare no checked exceptions. Overriding an accessor is rarely needed. Do the work in the constructor so the field holds the right value and the generatedpublic agrees with the accessor.equals
What the compiler rejects
The rules are easiest to learn from the errors. The program compiles eight tiny records in memory with the javax.toolsjavac
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
// Compiles small records in memory and prints what javac says about each one
public class ConstructorRules {
public static void main(String[] args) {
check("assigns this.min in a compact constructor",
"record R(int min) { R { this.min = min; } }");
check("return inside a compact constructor",
"record R(int min) { R { if (min < 0) return; } }");
check("extra constructor that does not call this(...)",
"record R(int min) { R() { } }");
check("canonical constructor less visible than the record",
"public record R(int min) { private R { } }");
check("compact and explicit canonical constructor together",
"record R(int min) { R { } R(int min) { this.min = min; } }");
check("explicit canonical constructor that forgets a field",
"record R(int min, int max) { R(int min, int max) { this.min = min; } }");
check("accessor with the wrong return type",
"record R(int min) { public long min() { return min; } }");
check("valid: parameter reassigned, extra constructor delegates",
"record R(int min) { R { min = Math.abs(min); } R() { this(0); } }");
}
static void check(String label, String source) {
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
JavaFileObject file = new SimpleJavaFileObject(
URI.create("string:///R.java"), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
};
boolean ok = javac.getTask(null, null, diags, List.of("-d", System.getProperty(
"java.io.tmpdir")), null, List.of(file)).call();
System.out.println(label + ":");
if (ok) {
System.out.println(" compiles");
}
for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
String text = d.getMessage(Locale.ENGLISH).strip();
String msg = String.join(" ", text.split("\\s*\\n\\s*"));
System.out.println(" error: " + msg);
}
}
}
Output:
assigns this.min in a compact constructor:
error: cannot assign a value to final variable min
return inside a compact constructor:
error: invalid compact constructor in record <init> (compact constructor must not have return statements)
extra constructor that does not call this(...):
error: constructor is not canonical, so its first statement must invoke another constructor of class R
canonical constructor less visible than the record:
error: invalid canonical constructor in record R (attempting to assign stronger access privileges; was public)
compact and explicit canonical constructor together:
error: constructor R(int) is already defined in record R
explicit canonical constructor that forgets a field:
error: variable max might not have been initialized
accessor with the wrong return type:
error: invalid accessor method in record R (return type of accessor method min() must match the type of record component min)
valid: parameter reassigned, extra constructor delegates:
compiles
- Assigning
in a compact constructor fails with "cannot assign a value to final variable". The field belongs to the compiler's automatic assignment; assign the parameterthis.min instead.min - A compact constructor cannot
early, because that would skip the field assignments.return - Any constructor that is not canonical must start with
, so no path can bypass the canonical constructor's checks.this(...) - The canonical constructor must be at least as visible as the record. A
record cannot hide its canonical constructor to force callers through a factory; the error says "attempting to assign stronger access privileges".public - Compact and explicit canonical constructors are the same constructor, so writing both is a duplicate definition. An explicit one must assign every field, or you get "might not have been initialized".
- An accessor must return exactly the component's type;
for anlong min() component is invalid. The last record compiles: reassigning a parameter and delegating withint are both allowed.this(0)
Defensive copy traps
Copying input looks simple, but each of these mistakes compiles and runs. The program uses an array component, a blank name and a list with a null
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CopyTraps {
// Copies only in the constructor: the accessor still hands out the internal array
record HalfSafe(int[] scores) {
HalfSafe {
scores = scores.clone();
}
}
// Copies on the way in and on the way out
record Safe(int[] scores) {
Safe {
scores = scores.clone();
}
@Override
public int[] scores() {
return scores.clone();
}
}
// Validates before normalizing: blank names slip through
record WrongOrder(String name) {
WrongOrder {
if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
}
name = name.strip();
}
}
record RightOrder(String name) {
RightOrder {
name = name.strip();
if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
}
}
}
// Keeps null elements but still cannot be changed from outside
record Slots(List<String> names) {
Slots {
names = Collections.unmodifiableList(new ArrayList<>(names));
}
}
public static void main(String[] args) {
HalfSafe half = new HalfSafe(new int[] {90, 80});
half.scores()[0] = 0;
System.out.println("HalfSafe after changing scores(): " + Arrays.toString(half.scores()));
Safe safe = new Safe(new int[] {90, 80});
safe.scores()[0] = 0;
System.out.println("Safe after changing scores(): " + Arrays.toString(safe.scores()));
System.out.println("WrongOrder(\" \") stored as [" + new WrongOrder(" ").name() + "]");
try {
new RightOrder(" ");
} catch (IllegalArgumentException e) {
System.out.println("RightOrder(\" \") rejected: " + e.getMessage());
}
List<String> withNull = Arrays.asList("Ana", null, "Ben");
try {
List.copyOf(withNull);
} catch (NullPointerException e) {
System.out.println("List.copyOf with a null element: NullPointerException");
}
Slots slots = new Slots(withNull);
System.out.println("Slots keeps the null: " + slots);
try {
slots.names().set(0, "Cho");
} catch (UnsupportedOperationException e) {
System.out.println("Slots.names() is read-only: UnsupportedOperationException");
}
}
}
Output:
HalfSafe after changing scores(): [0, 80]
Safe after changing scores(): [90, 80]
WrongOrder(" ") stored as []
RightOrder(" ") rejected: empty name
List.copyOf with a null element: NullPointerException
Slots keeps the null: Slots[names=[Ana, null, Ben]]
Slots.names() is read-only: UnsupportedOperationException
cloned the array in the constructor but returned the internal array from the generated accessor, so writing 0 throughHalfSafe changed the record toscores() . Arrays need a copy on the way in and on the way out, as in[0, 80] . Even then,Safe still compares the arrays by identity; aequals component avoids both problems.List<Integer> checkedWrongOrder before stripping, so three spaces passed the check and an empty name was stored. Normalize first, then validate the normalized value.isEmpty() throwsList.copyOf for aNullPointerException element. That is usually what you want; when nulls are legal, wrap a private copy withnull , which keeps theCollections.unmodifiableList(new ArrayList<>(names)) and still rejectsnull .set
Immutable updates: with-methods
Records have no setters. To "change" one, you create a copy with one component replaced, and a method named withX
public class Withers {
record Config(String host, int port, boolean tls) {
Config {
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("port " + port);
}
}
// "with" methods return a copy with one component changed
Config withHost(String newHost) {
return new Config(newHost, port, tls);
}
Config withPort(int newPort) {
return new Config(host, newPort, tls);
}
Config withTls(boolean newTls) {
return new Config(host, port, newTls);
}
}
public static void main(String[] args) {
Config base = new Config("localhost", 8080, false);
Config prod = base.withHost("api.example.com").withPort(443).withTls(true);
System.out.println("base: " + base);
System.out.println("prod: " + prod);
// Every wither goes through the canonical constructor, so validation still runs
try {
base.withPort(70000);
} catch (IllegalArgumentException e) {
System.out.println("withPort(70000) rejected: " + e.getMessage());
}
}
}
Output:
base: Config[host=localhost, port=8080, tls=false]
prod: Config[host=api.example.com, port=443, tls=true]
withPort(70000) rejected: port 70000
baseConfigprodwithPort(70000)config with { port = 443; }--enable-preview
Choosing where to put the code
| Goal | Use |
|---|---|
| Reject invalid values | Compact constructor that throws |
| Store a canonical form (trimmed, lower-case, lowest terms) | Compact constructor that reassigns the parameter, before any validation |
| Protect against later changes to a collection argument | List.copyOfSet.copyOfMap.copyOf |
| Array component | Clone in the constructor and in an overridden accessor, or use a List |
| Default values | Extra constructor calling this(...) |
| Creating from another unit or format | Static factory such as ofFahrenheitparse |
| Change one component | A withX |
Validation in the canonical constructor also runs when Java serialization recreates a record, as shown on the