Builder
Junior Always asked 6 min
On this page
The question
When would you use a Builder instead of a constructor?
30-second answer
When an object has several optional fields, when values should be named at the call site, or when it must be immutable yet needs validating as a whole. A builder collects values in named calls, then build() validates and creates the object. With two or three required fields and nothing optional, a constructor or a record is simpler.
Understand it
Assemble an immutable Email step by step
BuildAssemble an Email: put each call in the step it performs, then say what makes the result immutable.
Drag a piece, or select it and then select a place.
- Empty
- Empty
- Empty
- Empty
- Empty
View as text
On the left, a builder box with rows for to, subject and html, which fill in as calls are placed. On the right, an Email box that appears when build is placed and locks when its fields are final. Assemble an Email: put each call in the step it performs, then say what makes the result immutable.
The answers are: starts a builder and takes the required address takes Email.builder("ana@example.com"). Sets a value that the last call will validate takes .subject("Welcome"). Sets an optional flag, in any order takes .html(true). Validates and returns the finished object takes .build(). Why the finished object can never change takes private final fields, no setters.
The builder is mutable while you assemble. build() validates once and hands back an object that can never change.
On the left, a builder box with rows for to, subject and html, which fill in as calls are placed. On the right, an Email box that appears when build is placed and locks when its fields are final. Assemble an Email: put each call in the step it performs, then say what makes the result immutable.
The answers are: starts a builder and takes the required address takes Email.builder("ana@example.com"). Sets a value that the last call will validate takes .subject("Welcome"). Sets an optional flag, in any order takes .html(true). Validates and returns the finished object takes .build(). Why the finished object can never change takes private final fields, no setters.
The builder is mutable while you assemble. build() validates once and hands back an object that can never change.
Takeaway: A builder collects values one named call at a time, then build() validates them together and creates an object with only final fields.
Telescoping constructors vs a builder
CompareTelescoping: a constructor per optional field. To set html you must pass cc too, so the call holds a null and a bare true.
View as text
Two boxes on one layout: at the top what the Email class declares, at the bottom what a call looks like.
Telescoping: a constructor per optional field. To set html you must pass cc too, so the call holds a null and a bare true. The top box lists Email(to), Email(to, subject), Email(to, subject, cc) and Email(to, subject, cc, html). The call reads new Email(to, "Welcome", null, true), and marks ask what null and true mean.
Builder: one private constructor and one named method per field. The call skips cc and says what each value means. The top box lists a private constructor and the methods subject, cc, html and build. The call reads Email.builder(to).subject("Welcome").html(true).build(), and a mark says every value is named.
Two boxes on one layout: at the top what the Email class declares, at the bottom what a call looks like.
Telescoping: a constructor per optional field. To set html you must pass cc too, so the call holds a null and a bare true. The top box lists Email(to), Email(to, subject), Email(to, subject, cc) and Email(to, subject, cc, html). The call reads new Email(to, "Welcome", null, true), and marks ask what null and true mean.
Builder: one private constructor and one named method per field. The call skips cc and says what each value means. The top box lists a private constructor and the methods subject, cc, html and build. The call reads Email.builder(to).subject("Welcome").html(true).build(), and a mark says every value is named.
Takeaway: Telescoping constructors force a call to pass values it does not care about, in positions it must remember; a builder names each value and skips the rest.
In code
public final class Email {
private final String to;
private final String subject;
private final String cc;
private final boolean html;
private Email(Builder b) {
this.to = b.to; this.subject = b.subject; this.cc = b.cc; this.html = b.html;
}
public static Builder builder(String to) { return new Builder(to); }
public static final class Builder {
private final String to; // required
private String subject = "";
private String cc;
private boolean html;
private Builder(String to) { this.to = Objects.requireNonNull(to); }
public Builder subject(String subject) { this.subject = subject; return this; }
public Builder cc(String cc) { this.cc = cc; return this; }
public Builder html(boolean html) { this.html = html; return this; }
public Email build() {
if (subject.isBlank()) throw new IllegalStateException("subject is required");
return new Email(this);
}
}
}Email email = Email.builder("ana@example.com").subject("Welcome").html(true).build();
Email.builder("ana@example.com").build(); // IllegalStateException: subject is required
@Value // all fields private final, no setters
@Builder(toBuilder = true)
class EmailMessage {
@NonNull String to; // build() throws NullPointerException if missing
String subject;
@Builder.Default int retries = 3; // without @Builder.Default, build() gives 0
}
EmailMessage first = EmailMessage.builder().to("ana@example.com").subject("Welcome").build();
EmailMessage second = first.toBuilder().subject("Hello").build(); // a changed copyHttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/orders"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(5))
.POST(HttpRequest.BodyPublishers.ofString("{\"sku\":\"A1\"}"))
.build(); // immutable and ready to sendSolve it
Replace a seven-argument constructor after a swapped-argument bug
new User("Ana", "ana@example.com", null, null, true, false, 3) creates users. One caller passed the email as the name,
and the compiler said nothing because both are strings. Redesign object creation so this cannot happen again.
- Name the cause. Positional arguments of the same type can be swapped silently, and the
null,trueandfalsevalues say nothing about their meaning. - Name every value. A builder gives each value a method, such as
email("..."), so a swap is visible in review. - Keep required values required. Put them in the builder’s constructor, or check them in
build(). Optional values get defaults. - Weigh the cost. A builder adds code. With three or fewer fields a record or a static factory is enough; Lombok’s
@Builderremoves the boilerplate. - Check. A test that calls
build()without an email expects an exception.
final class User {
private final String name, email, phone;
private final boolean admin;
private User(Builder b) { name = b.name; email = b.email; phone = b.phone; admin = b.admin; }
static Builder builder(String name, String email) { return new Builder(name, email); }
static final class Builder {
private final String name, email;
private String phone;
private boolean admin;
private Builder(String name, String email) {
this.name = Objects.requireNonNull(name, "name");
this.email = Objects.requireNonNull(email, "email");
}
Builder phone(String phone) { this.phone = phone; return this; }
Builder admin(boolean admin) { this.admin = admin; return this; }
User build() { return new User(this); }
}
}
User ana = User.builder("Ana", "ana@example.com").admin(true).build();How to answer
- Named calls replace positional arguments such as
null, true. - Optional values are skipped, not passed as
null. build()is one place to validate fields together.- The result can have only
finalfields, because the builder holds the mutable state.
Common mistakes
- Adding a builder for a class with two required fields.
- Validating only in the setters, so a rule across two fields is never checked.
Follow-up questions
What is the telescoping constructor problem?
It is the chain of constructors a class grows as it gets optional fields: one with the required fields, then one more for each optional field, each calling the next. To set the last one you must pass all the others, so calls fill up with null and bare values. new Email(to, "Welcome", null, true) compiles but does not say what null and true mean.
- Same-typed parameters can be swapped by accident, and the compiler accepts it.
- Constructor count grows with each optional field.
- A builder or a record with named factories removes the positional guessing.
See it in the infographic: Telescoping constructors vs a builder
What does Lombok @Builder generate, and what should you watch out for?
It generates a static builder() method and a nested builder class with one method per field and a build() that calls an all-args constructor. Watch three things: a field initializer is ignored unless it has @Builder.Default, required fields are not enforced unless marked @NonNull, and nothing validates fields together unless you write it. toBuilder = true adds a way to copy and change.
@Value @Buildergives an immutable class with a builder.- Without
@Builder.Default,int retries = 3builds as 0. @NonNullthrowsNullPointerExceptionfrombuild(), at runtime rather than compile time.
@Value
@Builder(toBuilder = true)
class EmailMessage {
@NonNull String to;
String subject;
@Builder.Default int retries = 3;
} See it in the infographic: Telescoping constructors vs a builder
Why not just use a no-args constructor and setters?
Setters leave the object mutable forever and allow it to exist half-built: between new Email() and the last setter call, it is invalid and another thread or method can see it. A builder keeps the half-built state in a separate object and only hands out a complete, validated, immutable result, which is safe to share between threads.
- Setters cannot enforce a rule that spans two fields at a single moment.
- Immutable objects are thread-safe without synchronization.
- JPA (Jakarta Persistence API) entities and some serialization frameworks still need a no-args constructor.
See it in the infographic: Assemble an immutable Email step by step
Do records replace the Builder pattern?
Only for simple cases. A record gives an immutable class with a named accessor per field, and a compact constructor can validate. But it has one canonical constructor taking every component, so the positional problem remains when a record has many optional fields. Put a small builder on the record when calls start needing null, or use Lombok's @Builder on it.
- Use a record when every value is always given and fields are few.
- Use a builder when many fields are optional.
- Both end in the same place, an immutable object.
How does the fluent Builder you see in Java differ from the original GoF (Gang of Four) Builder?
The GoF version separates a director, which knows the steps, from interchangeable builders that produce different representations from those steps. The everyday Java version drops the director and the variety: a nested class with chained methods makes one product, and its goal is readable construction of an immutable object. Interviewers almost always mean the Java version, but naming the difference shows depth.
- GoF goal: the same steps produce different representations.
- Fluent goal: replace long constructors with named calls.
- Each fluent method returns
thisso calls can chain.
Can you reuse a builder after calling build()?
With the hand-written version, yes. Each build() creates a new object from the current values, so changing the builder and building again leaves the first object as it was. It is not thread-safe, because it is ordinary mutable state, so keep a builder local to one method.
How do you make a field required in a builder?
Take it as an argument of builder(to), so a caller cannot forget it and the compiler checks it. Or check it in build() and throw IllegalStateException, which only fails at runtime. For stronger compile-time checks, a step builder returns a different interface after each required call.
Where does the JDK (Java Development Kit) use the Builder pattern?
HttpRequest.newBuilder(uri).header(...).GET().build() is a textbook case, with an immutable result. StringBuilder is a builder in spirit: you append to it and toString() gives an immutable String. Stream.Builder and Locale.Builder are others. Spring has UriComponentsBuilder and WebClient.builder().
Check yourself
Show answers
- build(): Correct. It is the one point that sees all the values, so it validates them and calls the private constructor.
- subject("Welcome"): Incorrect. It only stores one value on the builder and returns the builder.
- Email.builder("ana@example.com"): Incorrect. It starts the builder and takes the required address, but nothing else is set yet.
Show answers
- A reader cannot tell what null and true mean, and the caller had to pass a value it does not care about.: Correct. Positional arguments hide meaning, which is what a builder's named methods fix.
- Passing null to a constructor always throws NullPointerException.: Incorrect. Nothing throws unless the constructor dereferences or checks the value.
- It creates four objects instead of one.: Incorrect. One new means one object; the problem is readability, not allocation.
Show answers
- 0: Correct. The builder has its own field defaulting to 0, unless the initializer is marked @Builder.Default.
- 3: Incorrect. The initializer is ignored without @Builder.Default; Lombok warns about this at compile time.
- build() throws an exception: Incorrect. Only a field marked @NonNull is checked at build time.