🌐
Baeldung
baeldung.com › home › java › implement the builder pattern in java
Implement the Builder Pattern in Java | Baeldung
April 22, 2024 - In the classic implementation of the Builder Pattern, we create a separate Builder inner class. This inner class contains methods to set each property of the constructed object. This structured approach facilitates a sequential configuration process, ensuring clarity and ease of use.
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › builder › java
Builder in Java / Design Patterns
January 1, 2026 - java.nio.ByteBuffer#put() (also in CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer) ... Identification: The Builder pattern can be recognized in a class, which has a single creation method and several methods to configure the resulting object.
🌐
GeeksforGeeks
geeksforgeeks.org › java › builder-pattern-in-java
Builder Method Design Pattern in Java - GeeksforGeeks
July 11, 2025 - The setter methods will now return Builder class reference. We will also have a build method to return instances of Server side class, i.e. outer class. ... // Java code to demonstrate Builder Pattern // Server Side Code final class Student { // final instance fields private final int id; private final String name; private final String address; public Student(Builder builder) { this.id = builder.id; this.name = builder.name; this.address = builder.address; } // Static class Builder public static class Builder { // instance fields private int id; private String name; private String address; pub
🌐
Project Lombok
projectlombok.org › features › Builder
@Builder
In the class containing the target: A builder() method, which creates a new instance of the builder. Each listed generated element will be silently skipped if that element already exists (disregarding parameter counts and looking only at names).
🌐
DigitalOcean
digitalocean.com › community › tutorials › builder-design-pattern-in-java
Builder Design Pattern in Java: Guide & Examples | DigitalOcean
August 3, 2022 - Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object. Let’s see how we can implement builder design pattern in java.
🌐
Vogella
vogella.com › tutorials › DesignPatternBuilder › article.html
Implementing the builder pattern in Java - Tutorial
February 26, 2026 - Once the product is fully configured, a build() method is invoked to create the final object. The builder can be implemented as an inner class or as a separate class.
🌐
HowToDoInJava
howtodoinjava.com › home › design patterns › creational › java builder pattern: build complex objects efficiently
Java Builder Pattern: Build Complex Objects Efficiently
October 14, 2023 - The builder pattern in Java allows for the step-by-step creation of large and complex immutable objects using the chained method calls.
🌐
DEV Community
dev.to › zeeshanali0704 › builder-design-pattern-in-java-a-complete-guide-2l41
Builder Design Pattern in Java – A Complete Guide - DEV Community
October 30, 2025 - The Builder Pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations. In simple terms, it allows building an object step-by-step using method chaining ...
🌐
Baeldung
baeldung.com › home › java › using lombok’s @builder annotation
Using Lombok's @Builder Annotation | Baeldung
July 25, 2024 - This annotation creates a method named builder() that returns a Builder for creating ImmutableClients.
Find elsewhere
🌐
Medium
medium.com › @thecodebean › builder-design-pattern-implementation-in-java-6adc6fd99ee0
Builder Design Pattern Java | The Code Bean | Medium
April 13, 2024 - In this blog post, we’ll explore how to implement the Builder Pattern in Java. Consider a scenario where we have a Person class with attributes firstNameand lastName , and we want to create instances of this class with different combinations of attributes. Here's what the Person class might look like: public class Person { private String firstName; private String lastName; private int age; // Other attributes and methods private Person() {} // Getter methods for attributes } To efficiently create instances of the Person class with various attribute combinations, we can implement the Builder Pattern.
🌐
Medium
serpro69.medium.com › the-builder-pattern-in-java-2c03fc6ccd16
The Builder pattern in Java — yet another Builder Pattern article? | by Serhii Prodan | Medium
April 1, 2019 - Just like with the constructor, we can check the passed parameters for any violations, most often inside the build() method or the setter method themselves, and throw IllegalStateException if any violations are present prior to creating an instance of the class. Though the Builder pattern does have disadvantages some minor disadvantages. First of all, you need to create a Builder object prior to creating the object of the class itself.
Top answer
1 of 13
1162

Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.

As Joshua Bloch states in Effective Java, 2nd Edition:

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.

2 of 13
352

Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

🌐
Medium
isaacpro01.medium.com › how-to-implement-a-simple-builder-pattern-in-java-54a1b9690cfa
How to implement a simple Builder Pattern in java | by Isaac Ssemugenyi | Medium
January 7, 2024 - At line 70 of the Car.java class, there is an inner Builder class inside the Car.java class. The Builder class has the public and static modifier which makes it accessible and instantiable outside of the Car class without creating an instance of the Car class. ... Inside the Builder class, we have a couple of encapsulated properties that correspond to the properties of the Car class and we methods that are accessible outside of the Builder class each returning the Builder class itself.
🌐
Baeldung
baeldung.com › home › architecture › automatic generation of the builder pattern with freebuilder
Automatic Generation of the Builder Pattern with FreeBuilder | Baeldung
January 8, 2024 - FreeBuilder is an open-source library that helps developers avoid the boilerplate code while implementing builder classes. It makes use of annotation processing in Java to generate a concrete implementation of the builder pattern.
🌐
DZone
dzone.com › articles › design-patterns-the-builder-pattern
Design Patterns: The Builder Pattern
December 13, 2016 - The Builder pattern allows us to write readable, understandable code to set up complex objects. It is often implemented with a fluent interface, which you may have seen in tools like Apache Camel or Hamcrest.
🌐
DZone
dzone.com › coding › languages › the builder design pattern in java
The Builder Design Pattern in Java
October 22, 2018 - It should return the same Builder object after setting the optional attribute. The final step is to provide a build() method in the builder class that will return the outer class object to the client.
Top answer
1 of 9
34

It's so you can be immutable AND simulate named parameters at the same time.

Person p = personBuilder
    .name("Arthur Dent")
    .age(42)
    .build()
;

That keeps your mitts off the person until it's state is set and, once set, won't let you change it. Yet every field is clearly labeled. You can't do this with just one class in Java.

It looks like you're talking about Josh Blochs Builder Pattern. This should not be confused with the Gang of Four Builder Pattern. These are different beasts. They both solve construction problems, but in fairly different ways.

Of course you can construct your object without using another class. But then you have to choose. You lose either the ability to simulate named parameters in languages that don't have them (like Java) or you lose the ability to remain immutable throughout the objects lifetime.

Immutable example, has no names for parameters

Person p = new Person("Arthur Dent", 42);

Here you're building everything with a single simple constructor. This will let you stay immutable but you loose the simulation of named parameters. That gets hard to read with many parameters. Computers don't care but it's hard on the humans.

Simulated named parameter example with traditional setters. Not immutable.

Person p = new Person();
p.name("Arthur Dent");
p.age(42);

Here you're building everything with setters and are simulating named parameters but you're no longer immutable. Each use of a setter changes object state.

So what you get by adding the class is you can do both.

Validation can be performed in the build() if a runtime error for a missing age field is enough for you. You can upgrade that and enforce that age() is called with a compiler error. Just not with the Josh Bloch builder pattern.

For that you need an internal Domain Specific Language (iDSL).

This lets you demand that they call age() and name() before calling build(). But you can't do it just by returning this each time. Each thing that returns returns a different thing that forces you to call the next thing.

Use might look like this:

Person p = personBuilder
    .name("Arthur Dent")
    .age(42)
    .build()
;

But this:

Person p = personBuilder
    .age(42)
    .build()
;

causes a compiler error because age() is only valid to call on the type returned by name().

These iDSLs are extremely powerful (JOOQ or Java8 Streams for example) and are very nice to use, especially if you use an IDE with code completion, but they are a fair bit of work to set up. I'd recommend saving them for things that will have a fair bit of source code written against them.

2 of 9
59

Why use/provide a builder class:

  • To make immutable objects — the benefit you've identified already.  Useful if the construction takes multiple steps.  FWIW, immutability should be seen a significant tool in our quest to write maintainable and bug free programs.
  • If the runtime representation of the final (possibly immutable) object is optimized for reading and/or space usage, but not for update.  String and StringBuilder are good examples here.  Repeatedly concatenating strings is not very efficient, so the StringBuilder uses a different internal representation that is good for appending — but not as good on space usage, and not as good for reading and using as the regular String class.
  • To clearly separate constructed objects from objects under construction.  This approach requires a clear transition from under-construction to constructed.  For the consumer, there is no way to confuse an under-construction object with a constructed object: the type system will enforce this.  That means sometimes we can use this approach to "fall into the pit of success", as it were, and, when making abstraction for others (or ourselves) to use (like an API or a layer), this can be a very good thing.
🌐
Medium
medium.com › @contactkumaramit9139 › builder-design-pattern-in-java-b1e33b403437
Builder Design Pattern in Java. Definition of Builder Pattern | by Amit Kumar | Medium
March 27, 2022 - For every optional field to be set, the Builder class exposes a setter-like method, which assigns the field’s value and returns the current Builder instance to build the object in a fluent way.
🌐
Medium
medium.com › @ajinkyabadve › builder-design-patterns-in-java-1ffb12648850
Builder Design Patterns in Java. While Considering the builder pattern… | by Ajinkya Badve | Medium
October 24, 2018 - Person person = new Person.Builder() .setAge(5) .setFirstName("Bob") .setHeight(6) .setAge(19) .build(); 1) Code is more maintainable if number of fields required to create object is more than 4 or 5. 2) Object Creation code less error-prone as user will know what they are passing because of explicit method call.