A compact constructor validates or normalizes fields before assignment.
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());
}
Range[lo=1, hi=10]
rejected: lo > hi
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