How do I close a file automatically using try-with-resources in Java?

Use a try-with-resources statement to close a file reader automatically. Java closes the reader when execution leaves the try block, even if reading fails.

In this example, you will open a UTF-8 text file with a BufferedReader and print it one line at a time.

Source code

Save the following code as TryWithResourcesExample.java:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class TryWithResourcesExample {
    void main() {
        Path path = Path.of("greeting.txt");

        try (BufferedReader reader =
                Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;

            while ((line = reader.readLine()) != null) {
                IO.println(line);
            }
        } catch (IOException exception) {
            System.err.println(
                    "Could not open, read, or close the file: "
                            + exception.getMessage());
        }
    }
}

Explanation

The declaration inside the parentheses after try opens the file and creates a BufferedReader:

try (BufferedReader reader =
        Files.newBufferedReader(path, StandardCharsets.UTF_8)) {

A BufferedReader implements AutoCloseable, so Java can call its close() method automatically. Closing the reader also closes the underlying file resource.

Inside the block, readLine() returns the next line without its line separator. It returns null when there are no more lines. The while condition assigns each result to line and checks whether it is null. A blank line returns an empty string, so it is still printed.

When the loop ends, Java closes the reader. If reading throws an exception, Java still attempts to close the reader before running the catch block. You do not need to call close() yourself or add a finally block for cleanup.

Run the example

Reuse greeting.txt from the previous example, or create it as a UTF-8 file with these contents:

Hello, Java!
Learning Java one snippet at a time.

From the directory containing both files, compile and run the program:

javac TryWithResourcesExample.java
java TryWithResourcesExample

Output

Hello, Java!
Learning Java one snippet at a time.

Use try-with-resources when you open a reader or writer yourself. Convenience methods such as Files.readString() and Files.writeString() already manage the file resource for you.

How do I write text to a file using Files.writeString() in Java?

Use Files.writeString() to save a string to a text file. By default, it uses UTF-8, creates the file if it does not exist, and replaces its contents if it already exists.

In this example, you will write a two-line message to a file named greeting.txt.

Source code

Save the following code as WriteStringExample.java:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteStringExample {
    void main() {
        Path path = Path.of("greeting.txt");

        String message = """
                Hello, Java!
                Learning Java one snippet at a time.
                """;

        try {
            Files.writeString(path, message);
            IO.println("Text written to " + path);
        } catch (IOException exception) {
            System.err.println(
                    "Could not write the file: " + exception.getMessage());
        }
    }
}

Explanation

Path.of("greeting.txt") creates a relative path. The program writes the file in its current working directory, which is normally the directory from which you run the java command.

The triple quotes (""") define a text block. This lets you write multiple lines without adding \n between them. Because the closing quotes are on their own line, the string also ends with a newline.

The following statement saves the message:

Files.writeString(path, message);

Files.writeString() encodes the string as UTF-8 and writes it as supplied. It does not add a newline of its own. The method handles opening and closing the file, so there is no writer to close in your code.

The catch block handles an IOException, which can occur if the directory is not writable. The success message appears only if the write completes without throwing an exception.

Run the example

Compile and run the file from a directory where you can create greeting.txt:

javac WriteStringExample.java
java WriteStringExample

The program prints:

Text written to greeting.txt

Open greeting.txt to see its contents:

Hello, Java!
Learning Java one snippet at a time.

Appending instead of replacing

To keep existing contents and add the message at the end, import java.nio.file.StandardOpenOption and replace the write statement with:

Files.writeString(
        path, message,
        StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);

CREATE creates the file if it is missing, and APPEND writes at the end if it already exists. If the existing text does not end with a newline, the appended text starts on the same line.

How do I read a text file using Files.readString() in Java?

You can use Files.readString() to read an entire text file into a single string. It preserves the file’s line separators, so the result can contain multiple lines.

In this example, you will read a UTF-8 text file and display its contents.

Source code

Save the following code as ReadStringExample.java:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadStringExample {
    void main() {
        Path path = Path.of("message.txt");

        try {
            String content = Files.readString(path, StandardCharsets.UTF_8);

            IO.print(content);
        } catch (IOException exception) {
            System.err.println("Could not read the file: " + exception.getMessage());
        }
    }
}

Prepare the text file

Create a file named message.txt in the directory from which you will run the program. Save it using UTF-8 encoding with the following contents:

Hello, Java!
Learning Java one snippet at a time.

Explanation

The example creates a Path representing the file location:

Path path = Path.of("message.txt");

This is a relative path. Java resolves it against the program’s current working directory, which may differ from the directory containing the source file.

Reading the contents

The following statement reads the entire file:

String content = Files.readString(path, StandardCharsets.UTF_8);

The first argument identifies the file. The second specifies how its bytes are decoded into characters.

Using StandardCharsets.UTF_8 makes the expected encoding explicit. The overload Files.readString(path) also uses UTF-8.

The method returns one string containing all the text, including any line separators in the file.

Displaying the text

The program prints the contents using:

IO.print(content);

IO.print() does not append a line separator. This lets the program display the text without adding an extra newline beyond those already in the file.

Handling read failures

Files.readString() can throw an IOException, for example when the file is missing or cannot be read.

The catch block handles that failure:

catch (IOException exception) {
    System.err.println("Could not read the file: " + exception.getMessage());
}

The error message goes to standard error, while the file contents go to standard output.

You do not need to close a reader yourself. Files.readString() manages the file resource and closes it when reading finishes or an error occurs.

Run the example

With message.txt in your current directory, compile and run the program:

javac ReadStringExample.java
java ReadStringExample

Output

Hello, Java!
Learning Java one snippet at a time.

Use Files.readString() for files that comfortably fit in memory. For large files, process the contents incrementally with a buffered reader or Files.lines() instead.

How Do I Create My First Spring MVC Application?

In the previous tutorial, we introduced Spring MVC and learned how the DispatcherServlet handles incoming HTTP requests.

In this tutorial, we will create our first working Spring MVC application using Java 25, Spring Framework 7.1.0, and Maven.

We will configure Spring MVC using Java classes instead of XML and deploy the application to Apache Tomcat 11.

We will not use Spring Boot in this example. This allows us to understand the basic components required to run a Spring MVC application.

1. Prerequisites

Before starting, make sure you have installed:

  • Java Development Kit (JDK) 25
  • Apache Maven 3.9 or later
  • Apache Tomcat 11
  • An IDE such as IntelliJ IDEA, Eclipse, or Visual Studio Code
  • Basic knowledge of Java classes and annotations

We will use the following technologies:

Technology Version Purpose
Java 25 Programming language
Spring Framework 7.1.0 Spring MVC framework
Jakarta Servlet API 6.1.0 Servlet interfaces
Apache Tomcat 11.x Web application server
Maven 3.9+ Build and dependency management

Tomcat 11 supports Jakarta Servlet 6.1, which is compatible with our application.

2. Create a Maven Project

Create a Maven project named spring-mvc-hello.

Use the following project information:

Group ID    : org.kodejava
Artifact ID : spring-mvc-hello
Version     : 1.0.0
Packaging   : war

Our application will have the following directory structure:

spring-mvc-hello/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── org/
        │       └── kodejava/
        │           └── springmvc/
        │               ├── config/
        │               │   ├── WebConfig.java
        │               │   └── WebAppInitializer.java
        │               └── controller/
        │                   └── HelloController.java
        └── webapp/
            └── WEB-INF/
                └── views/
                    └── hello.jsp

We will create each file step by step.

3. Configure Maven

Open the pom.xml file and configure the project dependencies.

We need spring-webmvc to provide the Spring MVC functionality and jakarta.servlet-api for the servlet interfaces.

The servlet API uses the provided scope because Tomcat already supplies it when the application is deployed.

Here is the complete pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
             http://maven.apache.org/POM/4.0.0
             https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kodejava</groupId>
    <artifactId>spring-mvc-hello</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>7.1.0</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-mvc-hello</finalName>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
                <configuration>
                    <release>25</release>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The war packaging type tells Maven to create a Web Application Archive that can be deployed to Tomcat.

The failOnMissingWebXml configuration allows us to build the application without a traditional web.xml deployment descriptor.

4. Create the Spring MVC Configuration

Next, create the WebConfig.java class in the config package.

package org.kodejava.springmvc.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import org.springframework.context.annotation.Bean;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.kodejava.springmvc.controller")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;
    }
}

Let’s understand the annotations and configuration.

@Configuration

The @Configuration annotation tells Spring that the class contains bean definitions and application configuration.

@EnableWebMvc

The @EnableWebMvc annotation enables Spring MVC configuration, including support for annotated controllers and request mappings.

@ComponentScan

The @ComponentScan annotation tells Spring where to find components such as classes annotated with @Controller.

In this example, Spring scans the org.kodejava.springmvc.controller package.

InternalResourceViewResolver

The InternalResourceViewResolver converts a logical view name into a JSP file path.

For example, when a controller returns:

return "hello";

Spring MVC resolves the view to:

/WEB-INF/views/hello.jsp

Placing JSP files under WEB-INF prevents users from accessing them directly through a browser. Instead, the pages are reached through Spring MVC controllers.

5. Register the DispatcherServlet

The DispatcherServlet is the central component of Spring MVC.

It receives HTTP requests and delegates them to the appropriate controller.

In older applications, developers commonly registered the DispatcherServlet using a web.xml file.

Modern Spring MVC applications can use Java configuration instead.

Create WebAppInitializer.java:

package org.kodejava.springmvc.config;

import org.springframework.web.servlet.support
        .AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

The AbstractAnnotationConfigDispatcherServletInitializer helps initialize Spring MVC when the servlet container starts the application.

We override three methods:

getRootConfigClasses()

Returns the configuration classes for the root application context. We return null because this simple application does not need a separate root context.

getServletConfigClasses()

Returns the Spring MVC configuration classes. In our application, this is WebConfig.class.

getServletMappings()

Defines which URL patterns are handled by the DispatcherServlet.

Using / allows the servlet to handle application requests while retaining the servlet container’s normal handling for JSP resources.

6. Create Your First Controller

Now we can create a controller that handles an HTTP request.

Create HelloController.java in the controller package.

package org.kodejava.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute(
                "message",
                "Hello, Spring MVC!"
        );

        return "hello";
    }
}

Let’s examine the controller.

@Controller

The @Controller annotation identifies the class as a Spring MVC controller.

Spring detects the class during component scanning and registers it as a bean.

@GetMapping

The @GetMapping("/hello") annotation maps HTTP GET requests to the hello() method.

When a user visits /hello, Spring MVC invokes this method.

Model

The Model interface allows us to pass data from the controller to the view.

In this example:

model.addAttribute("message", "Hello, Spring MVC!");

We add a model attribute named message.

The JSP page can access this attribute using Expression Language (EL).

Returning the View Name

The statement:

return "hello";

does not return the text hello to the browser.

Because the class uses @Controller, the returned string is interpreted as a logical view name.

Spring MVC uses our view resolver to locate hello.jsp.

7. Create the JSP View

Create the following file:

src/main/webapp/WEB-INF/views/hello.jsp

Add this HTML and JSP content:

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>My First Spring MVC Application</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f5f7fa;
            margin: 0;
            padding: 40px;
        }

        .container {
            max-width: 600px;
            margin: 60px auto;
            padding: 32px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
            text-align: center;
        }

        h1 {
            color: #2563eb;
        }

        p {
            color: #475569;
        }
    </style>
</head>
<body>
    <main class="container">
        <h1>${message}</h1>
        <p>My first Spring MVC application is running!</p>
    </main>
</body>
</html>

The expression:

${message}

reads the message attribute added by the controller.

The JSP engine evaluates this expression and inserts the value into the generated HTML.

For this example, the message is a fixed string defined by the application. In applications that display user-provided content, use output escaping to prevent cross-site scripting vulnerabilities.

8. Build the Application

Open a terminal in the project directory.

Run:

mvn clean package

Maven will compile the Java classes, resolve dependencies, and package the application into a WAR file.

If the build succeeds, you should see a message similar to:

[INFO] BUILD SUCCESS

The generated file is located at:

target/spring-mvc-hello.war

9. Deploy the Application to Tomcat

Download and extract Apache Tomcat 11 if you have not installed it already.

Copy the generated WAR file into Tomcat’s webapps directory.

On Linux or macOS, for example:

cp target/spring-mvc-hello.war \
   /path/to/tomcat/webapps/

On Windows PowerShell:

Copy-Item `
    target/spring-mvc-hello.war `
    C:\apache-tomcat-11\webapps\

Adjust the Tomcat directory to match your installation.

Start Tomcat using its startup script.

Linux or macOS:

/path/to/tomcat/bin/startup.sh

Windows:

C:\apache-tomcat-11\bin\startup.bat

If Tomcat is already running with automatic deployment enabled, it may deploy the WAR without a restart.

10. Test the Application

Open your browser and visit:

http://localhost:8080/spring-mvc-hello/hello

You should see a page displaying:

Hello, Spring MVC!

My first Spring MVC application is running!

The page will use the CSS styles defined in our JSP file.

You can also inspect the HTTP response using curl:

curl -i http://localhost:8080/spring-mvc-hello/hello

A successful request returns an HTTP 200 response with HTML content.

11. Understanding the Request Flow

Let’s review what happens when the browser requests our page.

Browser
   |
   | GET /spring-mvc-hello/hello
   v
Apache Tomcat
   |
   v
DispatcherServlet
   |
   v
HelloController
   |
   | model.addAttribute(...)
   | return "hello"
   v
View Resolver
   |
   v
/WEB-INF/views/hello.jsp
   |
   v
HTML Response
   |
   v
Browser

The request passes through these steps:

  1. The browser sends an HTTP GET request.
  2. Tomcat receives the request and forwards it to the DispatcherServlet.
  3. Spring MVC finds the controller method mapped to /hello.
  4. The controller adds the greeting message to the model.
  5. The controller returns the logical view name hello.
  6. The view resolver locates the JSP page.
  7. The JSP engine renders the page into HTML.
  8. Tomcat sends the generated HTML back to the browser.

This is the basic request-processing flow of a traditional Spring MVC application.

12. Common Problems

HTTP 404 Not Found

If the browser displays a 404 error, check the following:

  • The WAR file was deployed successfully.
  • The application context path is /spring-mvc-hello.
  • The controller uses @GetMapping("/hello").
  • The application started without deployment errors.

HTTP 500 Internal Server Error

A 500 error may indicate a problem with application configuration or JSP rendering.

Check the Tomcat logs in the logs directory for the underlying exception.

JSP File Cannot Be Found

Verify that your JSP file is located at:

src/main/webapp/WEB-INF/views/hello.jsp

Also verify that the prefix and suffix in WebConfig match the file location.

Java Version Errors

Make sure Maven and Tomcat are running with compatible Java versions.

Run:

java -version
mvn -version

The project is compiled for Java 25, so Tomcat must also run on Java 25 or a compatible newer Java runtime.

13. Summary

In this tutorial, we created our first Spring MVC application using Java configuration.

We learned how to:

  • Create a Maven-based Spring MVC project.
  • Configure Spring MVC with @EnableWebMvc.
  • Register the DispatcherServlet without web.xml.
  • Create a controller using @Controller and @GetMapping.
  • Pass data from a controller to a JSP view.
  • Configure an InternalResourceViewResolver.
  • Package the application as a WAR file.
  • Deploy and run the application on Apache Tomcat.

We now have a working Spring MVC application and understand how its main components work together.

In the next tutorial, How Does the DispatcherServlet Work in Spring MVC?, we will explore the internal request-processing mechanism, including handler mappings, handler adapters, and view resolution.

14. Maven Artifacts

The following Maven artifacts are required for this tutorial.

Spring Web MVC

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.1.0</version>
</dependency>

Maven artifact: org.springframework:spring-webmvc:7.1.0

Jakarta Servlet API

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven artifact: jakarta.servlet:jakarta.servlet-api:6.1.0

Maven Compiler Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.14.1</version>
</plugin>

Maven WAR Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.5.0</version>
</plugin>

Spring MVC automatically brings in several Spring dependencies through Maven’s transitive dependency management, so we do not need to declare each one manually.

References

How do I implement the Builder pattern in Java?

Suppose a reporting application produces a plain text summary for an email and an HTML fragment for a dashboard. Both reports contain a title and a sequence of items. We want to reuse the steps that assemble the report while allowing each output format to control how those steps are represented.

Builder is a Gang of Four creational pattern that separates the construction steps of a complex object from its representation. A director coordinates those steps through a builder interface. Concrete builders assemble the results in their own formats. The GoF describe this intent in their pattern catalog. Design Patterns by Gamma, Helm, Johnson, and Vlissides

This example uses a small report to make the construction sequence visible. The same approach can support richer reports with sections, tables, and summaries.

A complete example

Save the code as BuilderExample.java. It uses only standard Java classes and supports Java 8 or later.

package org.kodejava.pattern.builder;

import java.util.Arrays;
import java.util.List;

public class BuilderExample {
    interface ReportBuilder {
        void start(String title);
        void addItem(String item);
        void finish();
        String getResult();
    }

    static final class PlainTextReportBuilder implements ReportBuilder {
        private final StringBuilder content = new StringBuilder();

        @Override
        public void start(String title) {
            content.setLength(0);
            content.append(title).append("\n");
        }

        @Override
        public void addItem(String item) {
            content.append("- ").append(item).append("\n");
        }

        @Override
        public void finish() {
            // Plain text needs no closing markup.
        }

        @Override
        public String getResult() {
            return content.toString();
        }
    }

    static final class HtmlReportBuilder implements ReportBuilder {
        private final StringBuilder content = new StringBuilder();

        @Override
        public void start(String title) {
            content.setLength(0);
            content.append("<h1>").append(escape(title)).append("</h1><ul>");
        }

        @Override
        public void addItem(String item) {
            content.append("<li>").append(escape(item)).append("</li>");
        }

        @Override
        public void finish() {
            content.append("</ul>");
        }

        @Override
        public String getResult() {
            return content.toString();
        }

        private String escape(String value) {
            return value.replace("&", "&")
                    .replace("<", "<")
                    .replace(">", ">");
        }
    }

    static final class ReportDirector {
        void construct(ReportBuilder builder, String title, List<String> items) {
            builder.start(title);
            for (String item : items) {
                builder.addItem(item);
            }
            builder.finish();
        }
    }

    public static void main(String[] args) {
        ReportDirector director = new ReportDirector();
        List<String> items = Arrays.asList("Orders: 12", "Returns & exchanges: 2");
        ReportBuilder plainText = new PlainTextReportBuilder();
        director.construct(plainText, "Weekly report", items);
        System.out.print(plainText.getResult());

        ReportBuilder html = new HtmlReportBuilder();
        director.construct(html, "Weekly report", items);
        System.out.println(html.getResult());
    }
}

Compile and run it from the directory containing the source.

javac -d out BuilderExample.java
java -cp out org.kodejava.pattern.builder.BuilderExample

The output contains the plain text report followed by the HTML fragment.

Weekly report
- Orders: 12
- Returns & exchanges: 2
<h1>Weekly report</h1><ul><li>Orders: 12</li><li>Returns & exchanges: 2</li></ul>

The HTML builder escapes ampersands and angle brackets in text content. The sample’s ampersand becomes &amp;, keeping it as text inside the list item.

How the construction works

GoF role Example Responsibility
Builder ReportBuilder Declares the report construction steps.
Concrete builders PlainTextReportBuilder, HtmlReportBuilder Assemble the report in each format.
Director ReportDirector Calls the steps in the required order.
Products Plain text and HTML strings Hold the completed representations.
Client main() Chooses each builder and retrieves its result.

The director starts the report, adds each item, then finishes it. It uses the same sequence for both builders. The plain text builder adds line breaks and bullet markers. The HTML builder creates heading and list elements.

Although both results have Java type String, they represent different output formats. Each concrete builder owns the rules for assembling its representation.

The client calls getResult() after construction completes. Calling it earlier would return the content assembled so far. The director supplies the ordering contract for this example.

Each builder’s start() method clears its buffer, so a later construction using that builder replaces the previous report. Previously returned strings retain their contents. The mutable builders should be confined to one construction at a time.

Adding another representation

A new builder can implement the same operations for another report format. The client passes it to the director and retrieves the result after construction. A new construction operation, such as adding a table, requires updating the builder interface, implementations, and director where appropriate.

In Java APIs, you may also encounter fluent builders with chained configuration methods and a final build() call. This example makes the GoF construction process explicit through a director and interchangeable representations. Method chaining is an optional API choice.

When should I use Builder?

Builder fits a construction process with multiple steps that can be reused across different representations. Examples include document generation and assembling complex object structures from parsed input.

The additional interface and classes have a maintenance cost. For a short report with one fixed output format, a single formatting method can be sufficient. As formats and construction rules grow, builders give each representation a dedicated place to manage its assembly.

This continues the creational series after Factory Method and Abstract Factory. The series began with the existing Singleton article. Singleton pattern

Next, we will cover Prototype and create new objects by copying an existing instance.