Java 16: Record compact constructor for validation

A compact constructor validates or normalizes fields before assignment.

Code
record Range(int lo, int hi) {
    Range {
        if (lo > hi) throw new IllegalArgumentException("lo > hi");
    }
}
System.out.println(new Range(1, 10));
try { new Range(5, 2); } catch (IllegalArgumentException e) {
    System.out.println("rejected: " + e.getMessage());
}
Output
Range[lo=1, hi=10]
rejected: lo > hi
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26