A compact constructor runs before the fields are assigned, so it is the place to validate arguments and trim or copy incoming values.
record Customer(String email, int tokens) {
Customer {
Objects.requireNonNull(email, "email");
email = email.trim().toLowerCase();
if (tokens < 0) throw new IllegalArgumentException("tokens must not be negative");
}
}
System.out.println(new Customer(" Arul@Example.COM ", 10));
try {
new Customer("a@b.com", -1);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
Customer[email=arul@example.com, tokens=10]
rejected: tokens must not be negative
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-30