Java StringBuilder append() example

In this guide, you will learn about the StringBuilder append() method in Java programming and how to use it with an example.

1. StringBuilder append() Method Overview

Definition:

The append() method of the StringBuilder class is used to append data of various data types (like int, char, String, etc.) to the current sequence, thus making string concatenation efficient and fast.

Syntax:

stringBuilder.append(data)

Parameters:

- data: The data to be appended to the current sequence. This can be of various data types.

Key Points:

- StringBuilder is mutable, which means strings can be modified without creating new objects.

- The append() method is overloaded to accept all data types, including objects.

- It provides a much more performance-efficient way to concatenate strings, especially in loops or repeated operations, compared to using the + operator.

2. StringBuilder append() Method Example

public class StringBuilderAppendExample {
    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder("Hello, ");

        // Appending a String
        builder.append("World");
        System.out.println(builder);

        // Appending an integer
        builder.append(2023);
        System.out.println(builder);

        // Appending a character
        builder.append('!');
        System.out.println(builder);

        // Appending a boolean
        builder.append(true);
        System.out.println(builder);

        // Appending another StringBuilder
        StringBuilder anotherBuilder = new StringBuilder(" Have a nice day.");
        builder.append(anotherBuilder);
        System.out.println(builder);
    }
}

Output:

Hello, World
Hello, World2023
Hello, World2023!
Hello, World2023!true
Hello, World2023!true Have a nice day.

Explanation:

In the example:

1. We start by creating a StringBuilder object with the text "Hello, ".

2. We then use the append() method to concatenate various types of data:

- First, we append the string "World".

- Next, we append the integer 2023.

- We follow that with the character '!'.

- We also append a boolean value 'true'.

- Lastly, we append another StringBuilder object.

The append() method makes it easy to concatenate different data types in a more performance-efficient manner than using the + operator, especially in scenarios where strings are being concatenated multiple times.

Related Java StringBuilder class method examples

Comments