Checking a value inside the setter itself rejects bad input the moment it is supplied, rather than waiting until build() to report a problem that could be far from where it was introduced. Eager validation gives a more precise error at the exact call that caused it.
class Percentage {
static class Builder {
private int value;
Builder value(int v) {
if (v < 0 || v > 100) throw new IllegalArgumentException("out of range: " + v);
value = v;
return this;
}
int build() { return value; }
}
}
String outcome;
try {
new Percentage.Builder().value(150);
outcome = "accepted";
} catch (IllegalArgumentException e) {
outcome = "rejected eagerly: " + e.getMessage();
}
System.out.println(outcome);
rejected eagerly: out of range: 150
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-09-27