Builder Design Pattern in Java
The builder design pattern in Java constructs a complex object step by step through a separate builder object, then returns the finished result from a final build() call. Each step has a readable name, optional settings can be skipped, and the object can be validated and made immutable before anyone uses it.
It matters because constructors stop scaling once a class has many fields. A call such as new Shipment("BLR", "DEL", 2.5, true, false, 0) compiles happily even when two booleans are swapped. Builder replaces that guesswork with named steps. It is one of the creational design patterns, and the most common one in everyday Java code.
1. What Is the Builder Design Pattern?
The GoF intent is: "Separate the construction of a complex object from its representation so that the same construction process can create different representations."
In practice, Java developers use the name for two closely related designs:
- GoF Builder: a director runs a fixed sequence of steps against a builder interface, and different concrete builders turn the same steps into different results, such as HTML or plain text.
- Fluent builder (popularised by Effective Java): a static nested
Builderclass with chained setter-like methods and abuild()method. It solves the "too many constructor parameters" problem and produces immutable objects.
Both share the core idea: collect the settings in a temporary, mutable object, then create the real object in one go. That keeps the product immutable and lets construction rules live in one place.
2. Key Components
| Component | Responsibility | In the examples |
|---|---|---|
| Product | The complex object being built, usually immutable | Shipment, PaymentRequest |
| Builder | Declares the construction steps | ReportBuilder |
| Concrete Builder | Implements the steps and returns the result | HtmlReportBuilder, Shipment.Builder |
| Director (optional) | Calls the steps in a fixed order | MonthlySalesDirector |
| Client | Picks a builder, drives it or hands it to a director, and takes the result | main |
In a fluent builder the client plays the director's role itself, and the builder interface is often skipped. In the GoF form, the client creates a concrete builder, passes it to the director, and then reads the result from the builder.
3. When Is Builder Useful?
- Many optional parameters: a shipment with weight, fragile and insured flags, and a cash-on-delivery amount, most of which are usually left at their defaults.
- Same process, different outputs: a monthly sales report that must be produced as HTML for email and as plain text for logs.
- Strict validation: a payment request whose amount, currency and idempotency key must all be valid before it reaches a gateway.
4. UML Class Diagram
The diagram shows the GoF form from the Practical Example. The product here is the String returned by result().
ReportBuilder, and the client reads the finished product from the concrete builder it chose.ReportBuilderdeclares the steps; both concrete builders implement it (dashed line, hollow triangle).MonthlySalesDirectordepends only on the interface, so it works with any format.result()lives on the concrete builders, not the interface, because each one can return a different product type.- The client creates a concrete builder, hands it to the director, then calls
result().
5. Step-by-Step Execution Flow
- The client creates an
HtmlReportBuilder; its internal buffer is empty. - It calls
director.construct(htmlBuilder). - The director calls
title(), thenrow()once per region, thenfooter(). Each call appends to the builder's buffer. - The client calls
result()and receives the finished HTML. - Repeating steps 1 to 4 with a
PlainTextReportBuilderproduces text from the same director code.
With a fluent builder the flow is shorter: create the builder with the required values, chain the optional methods, and call build(), which validates and creates the product.
6. Real-World Use Cases
- E-commerce: shipment, order and search-query objects with many optional filters.
- Payments and banking: payment and transfer requests that must be complete and valid before submission.
- Notifications: messages with optional subject, CC list, attachments and priority.
- The JDK:
HttpRequest.newBuilder()andHttpClient.newBuilder()injava.net.http(Java 11+),Locale.BuilderandStream.builder()are real builders. - Spring:
ResponseEntity.ok().header(...).body(...),UriComponentsBuilder,WebClient.builder()and Spring Boot'sSpringApplicationBuilder. Lombok's@Buildergenerates fluent builders at compile time.
7. Problem Without the Pattern
A shipment class with telescoping constructors:
public class ShipmentWithoutBuilder {
static final class Shipment {
private final String origin;
private final String destination;
private final double weightKg;
private final boolean fragile;
private final boolean insured;
private final int codAmount;
// Telescoping constructors: each one adds a parameter
Shipment(String origin, String destination, double weightKg) {
this(origin, destination, weightKg, false, false);
}
Shipment(String origin, String destination, double weightKg, boolean fragile, boolean insured) {
this(origin, destination, weightKg, fragile, insured, 0);
}
Shipment(String origin, String destination, double weightKg, boolean fragile, boolean insured, int codAmount) {
this.origin = origin;
this.destination = destination;
this.weightKg = weightKg;
this.fragile = fragile;
this.insured = insured;
this.codAmount = codAmount;
}
@Override
public String toString() {
return origin + "->" + destination + " " + weightKg + "kg fragile=" + fragile + " insured=" + insured + " cod=" + codAmount;
}
}
public static void main(String[] args) {
// Intended: an insured, non-fragile parcel. Which boolean is which?
Shipment laptop = new Shipment("BLR", "DEL", 2.5, true, false, 0);
System.out.println(laptop);
}
}
BLR->DEL 2.5kg fragile=true insured=false cod=0
- Unreadable calls:
true, false, 0says nothing about meaning, so the laptop ships fragile and uninsured. - Constructor explosion: every new optional field adds another overload.
- No place for validation that spans several fields.
Setters (the JavaBeans style) fix readability but make the object mutable and leave it half-built between calls.
8. Solution Using the Pattern
Give Shipment a nested Builder. Required values go into the builder's constructor, optional ones get named methods such as insured() with sensible defaults, and build() checks the rules before creating an immutable shipment.
The swapped-boolean bug disappears because insured() cannot be mistaken for fragile(). A new option is one new builder method, not a new constructor, so existing calls keep compiling. The Basic Example shows this fix.
9. Builder Design Pattern in Java: Code Examples
Each example is a single file that runs on Java 21 with java FileName.java.
Basic Example: Fluent Shipment Builder
Problem: fix section 7 so that every option is named and invalid weights are rejected.
public class ShipmentBuilderDemo {
static final class Shipment {
private final String origin;
private final String destination;
private final double weightKg;
private final boolean fragile;
private final boolean insured;
private final int codAmount;
private Shipment(Builder builder) { // only the builder can create a Shipment
this.origin = builder.origin;
this.destination = builder.destination;
this.weightKg = builder.weightKg;
this.fragile = builder.fragile;
this.insured = builder.insured;
this.codAmount = builder.codAmount;
}
static Builder builder(String origin, String destination) { // required fields up front
return new Builder(origin, destination);
}
@Override
public String toString() {
return origin + "->" + destination + " " + weightKg + "kg fragile=" + fragile + " insured=" + insured + " cod=" + codAmount;
}
static final class Builder {
private final String origin;
private final String destination;
private double weightKg = 0.5; // sensible defaults for optional fields
private boolean fragile;
private boolean insured;
private int codAmount;
private Builder(String origin, String destination) {
this.origin = origin;
this.destination = destination;
}
Builder weightKg(double weightKg) { this.weightKg = weightKg; return this; }
Builder fragile() { this.fragile = true; return this; }
Builder insured() { this.insured = true; return this; }
Builder cashOnDelivery(int amount) { this.codAmount = amount; return this; }
Shipment build() {
if (weightKg <= 0 || weightKg > 30) {
throw new IllegalStateException("Weight must be between 0 and 30 kg, was " + weightKg);
}
return new Shipment(this);
}
}
}
public static void main(String[] args) {
Shipment laptop = Shipment.builder("BLR", "DEL").weightKg(2.5).insured().build();
Shipment vase = Shipment.builder("JAI", "MUM").weightKg(4).fragile().insured().cashOnDelivery(1800).build();
Shipment letter = Shipment.builder("PNQ", "HYD").build();
System.out.println(laptop);
System.out.println(vase);
System.out.println(letter);
try {
Shipment.builder("BLR", "CCU").weightKg(45).build();
} catch (IllegalStateException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Important classes and methods
Shipmenthas onlyfinalfields and a private constructor that takes the builder.Shipment.builder(origin, destination)forces the two required values.- Each optional method returns
this, which allows chaining. build()validates, then creates the product.
Expected output
BLR->DEL 2.5kg fragile=false insured=true cod=0
JAI->MUM 4.0kg fragile=true insured=true cod=1800
PNQ->HYD 0.5kg fragile=false insured=false cod=0
Rejected: Weight must be between 0 and 30 kg, was 45.0
How it runs
- The laptop is now insured and not fragile, exactly as written.
- The letter uses every default, including 0.5 kg.
- The 45 kg parcel fails in
build(), so no invalid shipment ever exists.
Practical Example: Sales Report with a Director
Problem: produce the same monthly report as HTML and as plain text without duplicating the report logic.
import java.util.List;
public class SalesReportDemo {
record RegionSales(String region, int orders) { }
// Builder: the steps every report format supports
interface ReportBuilder {
void title(String text);
void row(String label, int value);
void footer(String text);
}
// Concrete builder 1: HTML
static final class HtmlReportBuilder implements ReportBuilder {
private final StringBuilder html = new StringBuilder();
public void title(String text) { html.append("<h1>").append(text).append("</h1>\n<table>\n"); }
public void row(String label, int value) { html.append(" <tr><td>").append(label).append("</td><td>").append(value).append("</td></tr>\n"); }
public void footer(String text) { html.append("</table>\n<p>").append(text).append("</p>"); }
String result() { return html.toString(); }
}
// Concrete builder 2: plain text
static final class PlainTextReportBuilder implements ReportBuilder {
private final StringBuilder text = new StringBuilder();
public void title(String value) { text.append(value.toUpperCase()).append('\n'); }
public void row(String label, int value) { text.append(String.format("%-8s%6d%n", label, value)); }
public void footer(String value) { text.append("-- ").append(value); }
String result() { return text.toString(); }
}
// Director: knows the order of steps, not the format
static final class MonthlySalesDirector {
private final List<RegionSales> sales;
MonthlySalesDirector(List<RegionSales> sales) { this.sales = List.copyOf(sales); }
void construct(ReportBuilder builder) {
builder.title("Orders by region, October 2026");
int total = 0;
for (RegionSales s : sales) {
builder.row(s.region(), s.orders());
total += s.orders();
}
builder.footer("Total orders: " + total);
}
}
public static void main(String[] args) {
MonthlySalesDirector director = new MonthlySalesDirector(List.of(
new RegionSales("North", 1240), new RegionSales("South", 1875), new RegionSales("West", 960)));
HtmlReportBuilder html = new HtmlReportBuilder();
director.construct(html); // same steps...
System.out.println(html.result());
System.out.println();
PlainTextReportBuilder text = new PlainTextReportBuilder();
director.construct(text); // ...different representation
System.out.println(text.result());
}
}
Important classes and methods
ReportBuilderis the builder interface with three steps.MonthlySalesDirector.construct()owns the report's structure and the total.- Each concrete builder decides only how a step looks.
Expected output
<h1>Orders by region, October 2026</h1>
<table>
<tr><td>North</td><td>1240</td></tr>
<tr><td>South</td><td>1875</td></tr>
<tr><td>West</td><td>960</td></tr>
</table>
<p>Total orders: 4075</p>
ORDERS BY REGION, OCTOBER 2026
North 1240
South 1875
West 960
-- Total orders: 4075
How it runs
- The director runs the same calls twice, once per builder.
- The HTML builder wraps rows in table tags; the text builder pads columns.
- A Markdown or CSV format would be one new builder class, with no change to the director.
Real-World Enterprise Example: Step Builder for Payment Requests
Problem: a payment request must never be sent without an amount, currency and idempotency key, all values must be checked together, and variants must not change the original.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class PaymentRequestBuilderDemo {
// Immutable product; the compact constructor guards invariants however the record is created
record PaymentRequest(String merchantId, BigDecimal amount, String currency, String idempotencyKey,
String description, boolean capture, Map<String, String> metadata) {
PaymentRequest {
Objects.requireNonNull(merchantId, "merchantId");
Objects.requireNonNull(idempotencyKey, "idempotencyKey");
metadata = Map.copyOf(metadata); // unmodifiable copy
}
// Step builder: required fields in a fixed order, enforced by the compiler
static AmountStep forMerchant(String merchantId) {
return new Builder(merchantId);
}
Builder toBuilder() { // start a modified copy
Builder builder = new Builder(merchantId);
builder.amount = amount;
builder.currency = currency;
builder.idempotencyKey = idempotencyKey;
builder.description = description;
builder.capture = capture;
builder.metadata.putAll(metadata);
return builder;
}
}
interface AmountStep { CurrencyStep amount(String amount); }
interface CurrencyStep { KeyStep currency(String currency); }
interface KeyStep { Builder idempotencyKey(String key); }
static final class Builder implements AmountStep, CurrencyStep, KeyStep {
private final String merchantId;
private BigDecimal amount;
private String currency;
private String idempotencyKey;
private String description = "";
private boolean capture = true;
private final Map<String, String> metadata = new LinkedHashMap<>();
private Builder(String merchantId) { this.merchantId = merchantId; }
public CurrencyStep amount(String value) { this.amount = new BigDecimal(value); return this; }
public KeyStep currency(String value) { this.currency = value; return this; }
public Builder idempotencyKey(String key) { this.idempotencyKey = key; return this; }
// Optional settings, available only after every required step
Builder description(String value) { this.description = value; return this; }
Builder authorizeOnly() { this.capture = false; return this; }
Builder metadata(String key, String value) { this.metadata.put(key, value); return this; }
Builder changeAmount(String value) { this.amount = new BigDecimal(value); return this; }
PaymentRequest build() {
List<String> errors = new ArrayList<>(); // report every problem at once
if (amount.signum() <= 0) errors.add("amount must be positive");
if (!currency.matches("[A-Z]{3}")) errors.add("currency must be a 3-letter ISO code");
if (idempotencyKey.isBlank()) errors.add("idempotency key is required");
if (!errors.isEmpty()) {
throw new IllegalArgumentException(String.join("; ", errors));
}
return new PaymentRequest(merchantId, amount, currency, idempotencyKey, description, capture, metadata);
}
}
public static void main(String[] args) {
PaymentRequest order = PaymentRequest.forMerchant("M-42")
.amount("2499.00")
.currency("INR")
.idempotencyKey("ord-1001-try-1")
.description("Order 1001")
.metadata("channel", "mobile")
.build();
System.out.println(order);
// Hotel deposit: same request, authorised now and captured at checkout
PaymentRequest deposit = order.toBuilder()
.changeAmount("5000.00")
.idempotencyKey("deposit-77-try-1") // a new operation needs its own key
.authorizeOnly()
.description("Hotel deposit")
.build();
System.out.println(deposit);
System.out.println("Original unchanged: " + order.amount() + " capture=" + order.capture());
try {
PaymentRequest.forMerchant("M-42").amount("-10").currency("inr").idempotencyKey(" ").build();
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Important classes and methods
PaymentRequestis a record, so the product is immutable. Its compact constructor copies the metadata map into an unmodifiable map.- The step interfaces
AmountStep,CurrencyStepandKeyStepeach expose one method.build()is only reachable after all three, so forgetting a required field is a compile error. build()collects every validation error and reports them together.toBuilder()starts a new builder from an existing request, for variants.
Expected output
PaymentRequest[merchantId=M-42, amount=2499.00, currency=INR, idempotencyKey=ord-1001-try-1, description=Order 1001, capture=true, metadata={channel=mobile}]
PaymentRequest[merchantId=M-42, amount=5000.00, currency=INR, idempotencyKey=deposit-77-try-1, description=Hotel deposit, capture=false, metadata={channel=mobile}]
Original unchanged: 2499.00 capture=true
Rejected: amount must be positive; currency must be a 3-letter ISO code; idempotency key is required
How it runs
- The order request passes through the three required steps, then two optional ones.
- The deposit starts from
toBuilder(), changes the amount, key, capture flag and description, and builds a new record. - The original request is untouched.
- The invalid request fails with all three problems in one message.
10. Best Practices and Common Mistakes
Best practices
- Put required values in the builder's constructor or in step interfaces, and give optional ones defaults.
- Validate in
build(), and keep invariant checks in the product's constructor as well. - Copy mutable inputs such as lists and maps into the product.
- Thread safety: a builder is mutable and should stay on one thread; the immutable product it returns can be shared freely.
Common mistakes
- A public product constructor next to the builder, which bypasses validation.
- Reusing one builder for several objects and leaking settings between them.
- Returning mutable collections from the product.
- Overengineering: a builder for a class with two or three required fields, where a constructor or record is clearer.
11. When to Use and When Not to Use
Use it for objects with four or more parameters, several of them optional, for immutable objects that need validation across fields, and for test data where readable setup matters.
Avoid it for small classes and records with only required fields, for mutable entities that a framework fills in, such as JPA entities, and wherever a static factory method like Money.of(amount, currency) already reads well.
12. Advantages and Disadvantages
Advantages
- Readable construction with named steps.
- Immutable products with validated state.
- Defaults for optional values without overloads.
- Different representations from the same process (GoF form).
Disadvantages
- More code: a second class that mirrors the product's fields.
- Missing required fields are only caught at runtime unless you use a step builder.
- A small cost of one extra object per construction.
13. Comparison with Similar Patterns
| Aspect | Builder | Factory Method | Abstract Factory | Prototype |
|---|---|---|---|---|
| Focus | How one object is assembled | Which class to create | Which family to create | Copying a configured object |
| Creation | Several steps, then build() | One call | One call per product | One copy() call |
| Caller controls | Each setting | Little or nothing | Only the family | Only the changes after copying |
| Typical Java example | HttpRequest.newBuilder() | Collection.iterator() | java.sql.Connection | ArrayList.clone() |
Choose Builder when the difficulty is the number and combination of settings, a factory when the difficulty is choosing the class, and Prototype when a ready-made object already holds most of the state. Builders often appear inside other patterns: an Abstract Factory can return builders, and toBuilder() combines Prototype-style copying with Builder.
14. Summary
- The builder design pattern in Java builds complex objects step by step and returns them from
build(). - Purpose: readable construction, defaults, validation and immutability.
- Components: Product, Builder, Concrete Builder, optional Director, Client.
- The builder collects settings in a mutable object and creates the product in one go.
- Used for requests, shipments, reports, HTTP calls and test data.
- Benefits: no telescoping constructors, no swapped arguments, no half-built objects.
- Keep builders on one thread, keep products immutable, and skip the builder for small classes.
15. Java Design Pattern Interview Questions and Answers
Q1. Why not just use setters instead of a builder?
With setters, the object exists and can be used between calls, so it can be seen in a half-configured state. Setters also force the class to be mutable, which complicates sharing between threads and makes cross-field validation hard because there is no single "done" moment. A builder keeps the mutable phase in a separate object and creates the product only when build() confirms it is complete.
Q2. How do you write a builder for a class hierarchy?
Use a generic, self-referencing builder so that chained methods from the parent return the child builder's type. Each subclass builder overrides self() to return this.
abstract static class Notification {
abstract static class Builder<T extends Builder<T>> {
String recipient;
T recipient(String value) { recipient = value; return self(); }
abstract Notification build();
protected abstract T self();
}
}Q3. What should you watch out for with Lombok's @Builder?
Field initialisers are ignored by the generated builder unless the field is marked @Builder.Default. @Builder(toBuilder = true) is needed for copy-and-modify. For Jackson to deserialise through the builder, add @Jacksonized (Lombok 1.18.14 and later). Lombok also does not add validation, so checks still belong in the constructor.
Q4. A colleague shares one builder instance between request threads to "save objects". What goes wrong?
Builders are mutable and not thread-safe, so one request's values can end up in another request's object, or build() can see a mix of both. The saving is negligible because a builder is a small, short-lived object. Create a new builder per object, and share only the immutable results.
Q5. Should validation live in build() or in the product's constructor?
Ideally both: build() gives friendly, combined error messages, and the constructor guarantees invariants even if someone creates the product another way, such as through deserialization. For records, the compact constructor is the natural place for the invariant checks.