00:00

Builder Design Pattern in Java

Last updated:

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 Builder class with chained setter-like methods and a build() 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

ComponentResponsibilityIn the examples
ProductThe complex object being built, usually immutableShipment, PaymentRequest
BuilderDeclares the construction stepsReportBuilder
Concrete BuilderImplements the steps and returns the resultHtmlReportBuilder, Shipment.Builder
Director (optional)Calls the steps in a fixed orderMonthlySalesDirector
ClientPicks a builder, drives it or hands it to a director, and takes the resultmain

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().

Builder UML class diagram The Client uses MonthlySalesDirector and creates HtmlReportBuilder and PlainTextReportBuilder. The director uses the ReportBuilder interface, which both concrete builders implement. Each concrete builder has a result method. Client uses MonthlySalesDirector + construct(builder): void uses «interface» ReportBuilder + title(text): void + row(label, value): void + footer(text): void implements HtmlReportBuilder + title(), row(), footer() + result(): String PlainTextReportBuilder + title(), row(), footer() + result(): String «create», then result()
Builder (GoF form): the director drives any ReportBuilder, and the client reads the finished product from the concrete builder it chose.
  1. ReportBuilder declares the steps; both concrete builders implement it (dashed line, hollow triangle).
  2. MonthlySalesDirector depends only on the interface, so it works with any format.
  3. result() lives on the concrete builders, not the interface, because each one can return a different product type.
  4. The client creates a concrete builder, hands it to the director, then calls result().

5. Step-by-Step Execution Flow

  1. The client creates an HtmlReportBuilder; its internal buffer is empty.
  2. It calls director.construct(htmlBuilder).
  3. The director calls title(), then row() once per region, then footer(). Each call appends to the builder's buffer.
  4. The client calls result() and receives the finished HTML.
  5. Repeating steps 1 to 4 with a PlainTextReportBuilder produces 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() and HttpClient.newBuilder() in java.net.http (Java 11+), Locale.Builder and Stream.builder() are real builders.
  • Spring: ResponseEntity.ok().header(...).body(...), UriComponentsBuilder, WebClient.builder() and Spring Boot's SpringApplicationBuilder. Lombok's @Builder generates fluent builders at compile time.

7. Problem Without the Pattern

A shipment class with telescoping constructors:

ShipmentWithoutBuilder.java
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);
    }
}
Console
BLR->DEL 2.5kg fragile=true insured=false cod=0
  • Unreadable calls: true, false, 0 says 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.

ShipmentBuilderDemo.java
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

  • Shipment has only final fields 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

Console
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

  1. The laptop is now insured and not fragile, exactly as written.
  2. The letter uses every default, including 0.5 kg.
  3. The 45 kg parcel fails in build(), so no invalid shipment ever exists.

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

AspectBuilderFactory MethodAbstract FactoryPrototype
FocusHow one object is assembledWhich class to createWhich family to createCopying a configured object
CreationSeveral steps, then build()One callOne call per productOne copy() call
Caller controlsEach settingLittle or nothingOnly the familyOnly the changes after copying
Typical Java exampleHttpRequest.newBuilder()Collection.iterator()java.sql.ConnectionArrayList.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.