How do I build a string using StringBuilder in Java?

You can use StringBuilder to build text by appending values to a mutable sequence of characters.

In this example, you will combine a book’s title, author, and publication year into one string.

Source code

Save the following code as StringBuilderExample.java:

public class StringBuilderExample {
    void main() {
        String title = "Learning Java";
        String author = "Alice";
        int year = 2026;

        StringBuilder builder = new StringBuilder();

        builder.append("Title: ")
                .append(title)
                .append(System.lineSeparator())
                .append("Author: ")
                .append(author)
                .append(System.lineSeparator())
                .append("Year: ")
                .append(year);

        String details = builder.toString();

        IO.println(details);
    }
}

Explanation

Strings are immutable, so their contents cannot be changed after creation. A StringBuilder provides a mutable buffer that you can update while building text.

Create an empty builder using its constructor:

StringBuilder builder = new StringBuilder();

StringBuilder belongs to java.lang, so no import is required.

Appending values

The append() method adds a value to the end of the builder:

builder.append("Title: ");
builder.append(title);

These calls produce:

Title: Learning Java

You can append strings, characters, numbers, and other values. For example, the following call appends the text representation of the integer year:

builder.append(year);

Chaining method calls

Each append() call returns the same builder, allowing you to chain calls:

builder.append("Title: ")
        .append(title);

This updates one builder. It does not create a separate builder for each call.

The example uses System.lineSeparator() to insert the platform’s line separator between the book details.

Creating the final string

After building the text, call toString():

String details = builder.toString();

This returns a String containing the builder’s current text. Later changes to the builder do not change that string.

Finally, IO.println(details) prints the result.

Run the example

Compile and run the file:

javac StringBuilderExample.java
java StringBuilderExample

Output

Title: Learning Java
Author: Alice
Year: 2026

Use StringBuilder when you need to build text through repeated updates, especially inside a loop. For a short, fixed expression, string concatenation with + is often easier to read.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.