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

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 { ... } } the body has no parameter list, but it can use min and max as ordinary parameters. When the body finishes, the compiler appends this.min = min; this.max = max;. So the body can throw to reject the values, or reassign the parameters to store different values, and the fields receive whatever the parameters hold at the end.

Because every path leads through the canonical constructor, a check written there runs for new, for every static factory, for every extra constructor (they must call this(...)), for every with-method that builds a modified copy, and even for Java deserialization. An invalid record cannot exist.

The ways to customize record construction
FormSyntaxFields assignedBest for
Compact canonical constructorRange { ... }Automatically, after the bodyValidation, normalization, defensive copies
Explicit canonical constructorRange(int min, int max) { ... }By hand, every fieldCode that needs this.x and the parameter separately
Additional constructorRange() { this(0, 0); }Through this(...)Defaults (a named factory is often clearer)
Static factorystatic Range of(int a, int b)Through the canonical constructorAlternative inputs with a descriptive name
With-methodRange withMax(int m)Through the canonical constructorA 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 Java records.

Validating, normalizing and copying in a compact constructor

The program has one record for each of the three jobs. The name " Alice " has spaces on both sides so the normalization is visible, and the team list is changed by the caller after the record is created.

Java
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:

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
  • new Range(5, 1) was rejected with the message built in the constructor. Range 1 to 5 was accepted unchanged.
  • The brackets show that only Alice was stored. The body reassigned the name parameter, and the automatic assignment at the end copied that new value into the field.
  • Objects.requireNonNull(name, "name") produced the message name. Without it, the call to strip() would have thrown a less helpful NullPointerException one line later.
  • The caller added "Cho" to its own list, but the team still holds [Ana, Ben], and members().add throws UnsupportedOperationException. List.copyOf made a private, unmodifiable copy, so the record is now deeply immutable as long as the elements are.

Normalizing so that equal values are equal records

The generated equals compares fields exactly, so two records that mean the same thing are only equal if the constructor stores them the same way. Fractions and email addresses are good tests: 2/4 and 1/2 are the same number, and email domains are case-insensitive.

Java
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:

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 gcd returns 5 for (0, 5).
  • 1/6 + 1/3 is computed as 9/18 and normalized to 1/2 by the same constructor, since plus calls new.
  • Four fractions went into the TreeSet but only two remain, because 1/2, 2/4 and 5/10 became identical records.
  • The email typed as " Ana@Example.com" was found by ana@example.com. Locale.ROOT keeps the lower-casing independent of the machine's language settings (in a Turkish locale, "I".toLowerCase() is a dotless i).

An earlier version of this program built the set with Set.of(...) and failed with IllegalArgumentException: duplicate element: Fraction[num=1, den=2]. Set.of rejects duplicates, and after normalization they are duplicates.

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.

Java
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:

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 this(20.0), so the absolute-zero check also covers defaults.
  • ofFahrenheit(212) computed (212 - 32) × 5 / 9 = 100.0. A static factory has a name, which makes it clearer than a second constructor taking a double: new Temperature(212) could not say which scale it means.
  • -300 is below -273.15 and was rejected with the value in the message.
  • The overridden accessor celsius() just returns the field, to show the rules: it must be public, 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 generated equals agrees with the accessor.

What the compiler rejects

The rules are easiest to learn from the errors. The program compiles eight tiny records in memory with the javax.tools compiler API and prints what javac reports for each, so you can see the exact message you would get in your IDE.

Java
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:

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 this.min in a compact constructor fails with "cannot assign a value to final variable". The field belongs to the compiler's automatic assignment; assign the parameter min instead.
  • A compact constructor cannot return early, because that would skip the field assignments.
  • Any constructor that is not canonical must start with this(...), so no path can bypass the canonical constructor's checks.
  • The canonical constructor must be at least as visible as the record. A public record cannot hide its canonical constructor to force callers through a factory; the error says "attempting to assign stronger access privileges".
  • 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; long min() for an int component is invalid. The last record compiles: reassigning a parameter and delegating with this(0) are both allowed.

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 element, because each one breaks a different naive approach.

Java
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:

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
  • HalfSafe cloned the array in the constructor but returned the internal array from the generated accessor, so writing 0 through scores() changed the record to [0, 80]. Arrays need a copy on the way in and on the way out, as in Safe. Even then, equals still compares the arrays by identity; a List<Integer> component avoids both problems.
  • WrongOrder checked isEmpty() before stripping, so three spaces passed the check and an empty name was stored. Normalize first, then validate the normalized value.
  • List.copyOf throws NullPointerException for a null element. That is usually what you want; when nulls are legal, wrap a private copy with Collections.unmodifiableList(new ArrayList<>(names)), which keeps the null and still rejects 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 for each component makes that read naturally when chained. The port 70,000 is used because it is outside the valid range of 1 to 65,535.

Java
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:

Output
base: Config[host=localhost, port=8080, tls=false]
prod: Config[host=api.example.com, port=443, tls=true]
withPort(70000) rejected: port 70000

base is unchanged after the chain: each call returned a new Config, and prod has all three changes. withPort(70000) failed with the same message as the constructor would give, because the with-method calls the constructor. Writing these methods by hand is repetitive for records with many components. JEP 468 proposes a language-level form, config with { port = 443; }, but it is a candidate JEP: JDK 25 does not accept that syntax, even with --enable-preview.

Choosing where to put the code

Which construction form to use
GoalUse
Reject invalid valuesCompact 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 argumentList.copyOf, Set.copyOf, Map.copyOf in the compact constructor
Array componentClone in the constructor and in an overridden accessor, or use a List
Default valuesExtra constructor calling this(...), or a named static factory
Creating from another unit or formatStatic factory such as ofFahrenheit or parse
Change one componentA withX method that calls the canonical constructor

Validation in the canonical constructor also runs when Java serialization recreates a record, as shown on the records page. To take records apart again, see record patterns.