How to Use StringBuilder for Efficient String Concatenation

In Java, using StringBuilder is a common way to handle efficient string concatenation, especially when working with loops or when you need to concatenate a large number of strings. Unlike String, which is immutable, StringBuilder is mutable and modifies its internal character array without creating new objects, hence improving performance.

Here’s how you can use StringBuilder for efficient string concatenation:

1. Creating a StringBuilder instance

You can create a new instance of StringBuilder using its constructor:

StringBuilder sb = new StringBuilder();

You can also initialize it with an existing string:

StringBuilder sb = new StringBuilder("Hello");

2. Appending Strings

Use the .append() method to concatenate strings:

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString()); // Output: "Hello World"

Here, the append() method modifies the existing StringBuilder instance.


3. Inserting Strings

To insert a string at a specific position, use the .insert() method:

StringBuilder sb = new StringBuilder("Hello World");
sb.insert(6, "Beautiful ");
System.out.println(sb.toString()); // Output: "Hello Beautiful World"

4. Replacing Part of the String

You can replace part of the string using .replace():

StringBuilder sb = new StringBuilder("Hello Java");
sb.replace(6, 10, "World");
System.out.println(sb.toString()); // Output: "Hello World"

5. Reversing the String

You can reverse the string using .reverse():

StringBuilder sb = new StringBuilder("abcd");
sb.reverse();
System.out.println(sb.toString()); // Output: "dcba"

6. Deleting Characters or Substrings

You can use .delete() or .deleteCharAt() to remove parts of the string:

StringBuilder sb = new StringBuilder("Hello World");
sb.delete(5, 11); // Remove characters from index 5 to 10
System.out.println(sb.toString()); // Output: "Hello"

sb.deleteCharAt(0); // Remove the character at index 0
System.out.println(sb.toString()); // Output: "ello"

7. Converting Back to a String

Once you are done building the string, convert it back to a String using .toString():

StringBuilder sb = new StringBuilder("Hello");
String result = sb.toString();
System.out.println(result); // Output: "Hello"

8. StringBuilder in Loops

It is particularly useful when appending strings in loops to avoid the overhead of creating multiple String instances:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
    sb.append("Number ").append(i).append(", ");
}
System.out.println(sb.toString());
// Output: "Number 0, Number 1, Number 2, Number 3, Number 4, "

Example: Complete Code

Here’s a complete example that combines multiple methods:

public class StringBuilderExample {
    public static void main(String[] args) {
        // Create a StringBuilder
        StringBuilder sb = new StringBuilder("Example");

        // Append strings
        sb.append(" of").append(" StringBuilder");

        // Insert a string
        sb.insert(8, " java");

        // Replace a substring
        sb.replace(0, 7, "Demo");

        // Delete part of the string
        sb.delete(5, 10);

        // Reverse the string
        sb.reverse();

        // Convert back to String
        System.out.println(sb.toString());
    }
}

Output:

redliuBgnirtS fo omeD

Performance Comparison: String vs StringBuilder

Here’s a quick comparison of the performance:

  • String: Creates a new object for each concatenation, which is inefficient in loops.
  • StringBuilder: Reuses the same object and modifies its internal buffer, which is much faster.

So, whenever you’re performing a lot of string manipulations, especially in loops, it’s highly recommended to use StringBuilder.

How do I determine whether a string is a palindrome?

This code checks a string to determine if it is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forward.

package org.kodejava.lang;

public class PalindromeChecker {

    public static void main(String[] args) {
        String text = "Sator Arepo Tenet Opera Rotas";

        PalindromeChecker checker = new PalindromeChecker();
        System.out.println("Is palindrome = " + checker.isPalindrome(text));
    }

    /**
     * This method checks the string for palindrome. We use StringBuilder to
     * reverse the original string.
     *
     * @param text a text to be checked for palindrome.
     * @return <code>true</code> if a text is palindrome.
     */
    private boolean isPalindrome(String text) {
        System.out.println("Original text = " + text);

        String reverse = new StringBuilder(text).reverse().toString();
        System.out.println("Reverse text  = " + reverse);

        // Compare the original text with the reverse one and ignoring its case
        return text.equalsIgnoreCase(reverse);
    }
}

How do I insert a string in the StringBuilder?

package org.kodejava.lang;

public class StringBuilderInsert {
    public static void main(String[] args) {
        StringBuilder alphabets = new StringBuilder("abcdfghopqrstuvwxyz");
        System.out.println("alphabets = " + alphabets);

        //  |a|b|c|d|f|g|h|i|....
        //  0|1|2|3|4|5|6|7|8|...
        //
        // From the above sequence you can see that the index of the string is
        // started from 0, so when we insert a string in the fourth offset it
        // means it will be inserted after the "d" letter. There are other overload
        // version of this method that can be used to insert other type of data
        // such as char, int, long, float, double, Object, etc.
        alphabets.insert(4, "e");
        System.out.println("alphabets = " + alphabets);

        // Here we insert an array of characters to the StringBuilder.
        alphabets.insert(8, new char[] {'i', 'j', 'k', 'l', 'm', 'n'});
        System.out.println("alphabets = " + alphabets);
    }
}

The result of the code snippet above:

alphabets = abcdfghopqrstuvwxyz
alphabets = abcdefghopqrstuvwxyz
alphabets = abcdefghijklmnopqrstuvwxyz

How do I remove substring from StringBuilder?

This example demonstrate you how to use the StringBuilder delete(int start, int end) and deleteCharAt(int index) to remove a substring or a single character from a StringBuilder.

package org.kodejava.lang;

public class StringBuilderDelete {
    public static void main(String[] args) {
        StringBuilder lipsum = new StringBuilder("Lorem ipsum dolor sit " +
                "amet, consectetur adipisicing elit.");
        System.out.println("lipsum = " + lipsum);

        // We'll remove a substring from this StringBuilder starting from
        // the first character to the 28th character.
        lipsum.delete(0, 28);
        System.out.println("lipsum = " + lipsum);

        // Removes a char from the StringBuilder. In the example below we
        // remove the last character.
        lipsum.deleteCharAt(lipsum.length() - 1);
        System.out.println("lipsum = " + lipsum);
    }
}

The result of the code snippet above:

lipsum = Lorem ipsum dolor sit amet, consectetur adipisicing elit.
lipsum = consectetur adipisicing elit.
lipsum = consectetur adipisicing elit