You're on the right track by understanding the immutability of the String class.

Based on [1] and [2], here are some cases where each type of implementation is recommended:

1. Simple String Concatenation

String answer = firstPart + "." + secondPart;

This is syntactic sugar for

String answer = new StringBuilder(firstPart).append("."). append(secondPart).toString();

This is actually quite performant and is the recommended approach for simple string concatenation [1].

2. Stepwise Construction

String answer = firstPart;
answer += ".";
answer += secondPart;

Under the hood, this translates to

String answer = new StringBuilder(firstPart).toString(); 
answer = new StringBuilder(answer).append(".").toString(); 
answer = new StringBuilder(answer).append(secondPart).toString();

This creates a temporary StringBuilder and intermediate String objects which are inefficient [1]. Especially if the intermediate results are not used.

Use StringBuilder in this case.

3. For Loop Construction and Scaling For Larger Collections

String result = "";

for(int i = 0; i < numItems(); i++) 
  result += lineItem(i);

return result;

The above code is O(n^2), where n is number of strings. This is due to the immutability of the String class and due to the the fact that when concatenating two strings, the contents of both are copied [2].

So it may be fine for a few fixed length items, but it will not scale. In such cases, use StringBuilder.

StringBuilder sb = new StringBuilder(numItems() * LINE_SIZE);

for(int i = 0; i < numItems(); i++)
  sb.append(lineItem(i));

return b.toString();

This code is O(n) time, where n is number of items or strings. So as the number of strings gets larger, you will see the difference in performance [2].

This code pre-allocates an array in the initialization of StringBuilder, but even if a default size array is used, it will be significantly faster than the previous code for a large number of items [2].

Summary

Use string concatenation if you are concatenating only a few strings or if performance is not of importance (i.e. a demonstration/toy-application). Otherwise, use StringBuilder or consider processing the string as a character array [2].

References:

[1] Java Performance: The Definitive Guide by Scott Oaks: Link

[2] Effective Java 3rd Edition by Joshua Bloch: Link

Answer from mukundvemuri on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-class-in-java-with-examples
StringBuilder Class in Java - GeeksforGeeks
Initial StringBuilder: GeeksforGeeks After append: GeeksforGeeks is awesome! Explanation : This example demonstrates the use of the append() method in StringBuilder to add text at the end of an existing string.
Published   May 8, 2026
Top answer
1 of 2
9

You're on the right track by understanding the immutability of the String class.

Based on [1] and [2], here are some cases where each type of implementation is recommended:

1. Simple String Concatenation

String answer = firstPart + "." + secondPart;

This is syntactic sugar for

String answer = new StringBuilder(firstPart).append("."). append(secondPart).toString();

This is actually quite performant and is the recommended approach for simple string concatenation [1].

2. Stepwise Construction

String answer = firstPart;
answer += ".";
answer += secondPart;

Under the hood, this translates to

String answer = new StringBuilder(firstPart).toString(); 
answer = new StringBuilder(answer).append(".").toString(); 
answer = new StringBuilder(answer).append(secondPart).toString();

This creates a temporary StringBuilder and intermediate String objects which are inefficient [1]. Especially if the intermediate results are not used.

Use StringBuilder in this case.

3. For Loop Construction and Scaling For Larger Collections

String result = "";

for(int i = 0; i < numItems(); i++) 
  result += lineItem(i);

return result;

The above code is O(n^2), where n is number of strings. This is due to the immutability of the String class and due to the the fact that when concatenating two strings, the contents of both are copied [2].

So it may be fine for a few fixed length items, but it will not scale. In such cases, use StringBuilder.

StringBuilder sb = new StringBuilder(numItems() * LINE_SIZE);

for(int i = 0; i < numItems(); i++)
  sb.append(lineItem(i));

return b.toString();

This code is O(n) time, where n is number of items or strings. So as the number of strings gets larger, you will see the difference in performance [2].

This code pre-allocates an array in the initialization of StringBuilder, but even if a default size array is used, it will be significantly faster than the previous code for a large number of items [2].

Summary

Use string concatenation if you are concatenating only a few strings or if performance is not of importance (i.e. a demonstration/toy-application). Otherwise, use StringBuilder or consider processing the string as a character array [2].

References:

[1] Java Performance: The Definitive Guide by Scott Oaks: Link

[2] Effective Java 3rd Edition by Joshua Bloch: Link

2 of 2
5

You cannot change the original string because it is immutable therefore having String s = ""; every operation like

s += "something";

will create and reassign new object (probably it will also add a little bit of work for GC in near future). On he other hand modifying StringBuilder is (usually) not creating new object (indeed it is happening just once at the very end when calling toString() method on builder instance)

Because of this it is common to use StringBuilder when you are modifying string many many times (for example in some long loops).

Still it is common error to overuse StringBuilder - it may be example of premature optimization


Read also:

  • Is it better to reuse a StringBuilder in a loop?
Discussions

[Java] What exactly is stringBuilder and why use it instead of a traditional String?
If I remember correctly, Java will do things in memory that you might not be aware of. String is an example of this, it will allocate additional memory because it creates a new string object when doing += in Java More on reddit.com
🌐 r/learnprogramming
5
1
January 6, 2021
Question about StringBuilder
When you create a String literal(anytime you do 'Hello world", even passing it to a function) it'll most likely be interned, so if you try to use that same string literal elsewhere it'll be reused. It's more clear to define to a constant/variable and reuse it if it'll truly be reused a lot though . More on reddit.com
🌐 r/javahelp
27
2
June 22, 2024
Strings vs StringBuilder

You're not really going to find a better way to visualise it really unless you drew custom graphics, they do the same thing.

The explanation is the important part:

On each concatenation a new copy of the string is created, and is copied char by char. Iter 1 requires x chars copied. Iter 2 = 2x, 3= 3x and so on. Overall this equates to O(x + 2x +3x ..... +Kx) == O( xn2 ).

StringBuilder does the same functionality but uses a resizable array of all the strings and only copies them 1 time into a string when needed

More on reddit.com
🌐 r/learnjava
6
1
June 8, 2022
What happens when i use toString() method on a StringBuilder?
More-or-less. It does indeed copy the data from the StringBuilder (according to the documentation), so in theory the amount of work is proportional to the length of the string. However, looking at the source code, it uses a fairly low-level bulk copy operation under the hood. So is likely faster in practice than manually looping through a char array. More on reddit.com
🌐 r/learnjava
7
31
June 30, 2020
People also ask

What is string builder in Java?
The StringBuilder class in Java is a mutable sequence of characters that allows you to modify the contents of a string. It is faster than StringBuffer and not thread-safe.
🌐
theknowledgeacademy.com
theknowledgeacademy.com › blog › stringbuilder-java
StringBuilder in Java: Constructors, Methods, and Examples
What are some of the benefits of StringBuilder?
It reduces memory usage and improves the performance of string operations, as it does not create a new object with every update. Besides, it provides an API compatible with StringBuffer but with no guarantee of synchronisation, making it suitable for single-threaded environments. Moreover, it offers various methods to manipulate strings, such as appending, inserting, deleting, and reversing.
🌐
theknowledgeacademy.com
theknowledgeacademy.com › blog › stringbuilder-java
StringBuilder in Java: Constructors, Methods, and Examples
List out some Java String builder methods
Here are some of the common methods of the StringBuilder class: 1) append(): This method appends the string representation of any type of argument to the sequence. 2) insert(): This method inserts the string representation of any type of argument at a specified position in the sequence. 3) delete(): This method removes the characters in a substring of the sequence. 4) reverse(): This method reverses the order of the characters in the sequence. 5) toString(): This method returns a string representing the data in the sequence.
🌐
theknowledgeacademy.com
theknowledgeacademy.com › blog › stringbuilder-java
StringBuilder in Java: Constructors, Methods, and Examples
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › buffers.html
The StringBuilder Class (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
Then convert the string back into a string builder using the StringBuilder(String str) constructor. The StringDemo program that was listed in the section titled "Strings" is an example of a program that would be more efficient if a StringBuilder were used instead of a String.
🌐
Codecademy
codecademy.com › docs › java › stringbuilder
Java | StringBuilder | Codecademy
April 24, 2025 - StringBuffer is another mutable sequence class in Java that is similar to StringBuilder. Both classes provide methods for modifying character sequences, but they differ in significant ways: This example demonstrates the basic creation and usage of StringBuilder:
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › base-types › stringbuilder
Using the StringBuilder Class in .NET - .NET | Microsoft Learn
Dim myStringBuilder As New StringBuilder("Hello World!", 25) Additionally, you can use the read/write Capacity property to set the maximum length of your object. The following example uses the Capacity property to define the maximum object length.
Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › javas-stringbuilder-append-method-explained-500b2ef84ec0
Java’s StringBuilder.append() Method Explained | Medium
August 6, 2024 - Learn the mechanics, performance benefits, and use cases of Java's StringBuilder.append() method for efficient string concatenation and data manipulation.
🌐
Medium
medium.com › @AlexanderObregon › understanding-string-vs-stringbuilder-in-java-50448cbbf253
Java String vs StringBuilder: Key Differences | Medium
April 26, 2024 - In this example, we’re appending numbers from 0 to 9999 to a String and a StringBuilder. The time taken by StringBuilder is significantly less than that taken by String. The choice between String and StringBuilder in Java depends on your specific ...
🌐
The Knowledge Academy
theknowledgeacademy.com › blog › stringbuilder-java
StringBuilder in Java: Constructors, Methods, and Examples
January 1, 2009 - Explore this blog on Stringbuilder in java. It is used to create mutable strings. Learn about What it is, how it works, how to use, syntax, examples and more!
🌐
Codecademy
codecademy.com › docs › java › stringbuilder › .insert()
Java | StringBuilder | .insert() | Codecademy
August 22, 2022 - The following example creates a StringBuilder with a specified String and then uses the .insert() method to change it: ... Hello World! Hello to the World! ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more! ... Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
🌐
Reddit
reddit.com › r/learnprogramming › [java] what exactly is stringbuilder and why use it instead of a traditional string?
r/learnprogramming on Reddit: [Java] What exactly is stringBuilder and why use it instead of a traditional String?
January 6, 2021 -

Going through firecode.io and saw this solution (to replace spaces with a certain string)

public static String replace(String a, String b) {

    String ans = "";
    for (char c: a.toCharArray() ){
        if (c == ' '){ ans += b; }
        else { ans += c; }
    }
    return ans;

}

A user commented and said:

Use StringBuilder instead - it's more efficient! String does not allow appending. Each method you invoke on a String creates a new object and returns it. This is because String is immutable - it cannot change its internal state. On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.

I'm curious about this and wanted to ask (I'm new to Java):

  • If a traditional 'String' is immutable, why am I able to use it in a "+=" operation to append a char at the end?

  • So when you use the "+=" operation, the computer instantiates a brand new String object each and every time you do it? So effectively I'm creating/destroying multiple String objects over and over again with every "+="?

  • Coming from C++, I see a lot of the "+=" operation when working with strings. Is it the same situation in C++ as it is expressed here in Java?

🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuffer-vs-stringbuilder
StringBuffer vs StringBuilder in Java - GeeksforGeeks
StringBuffer and StringBuilder are classes in Java used to create and modify mutable strings. Unlike the String class, their content can be changed without creating a new object.
Published   May 28, 2026
🌐
Slideshare
slideshare.net › home › engineering › 3.7_stringbuilder.pdf
3.7_StringBuilder.pdf
public StringBuilder delete(int startIndex, int endIndex) It is used to delete the string from specified startIndex and endIndex.
🌐
Baeldung
baeldung.com › home › java › java string › concatenating strings in java
Concatenating Strings in Java | Baeldung
May 8, 2025 - Internally, StringBuilder maintains a mutable array of characters. In our code sample, we’ve declared this to have an initial size of 100 through the StringBuilder constructor. Because of this size declaration, the StringBuilder can be a very efficient way to concatenate Strings.
🌐
ZetCode
zetcode.com › java › stringbuilder
Java StringBuilder - mutable Java strings with StringBuilder
Java String is immutable while StringBuilder is mutable. ... package com.zetcode; public class MutableImmutableEx { public static void main(String[] args) { var word = "rock"; var word2 = word.replace('r', 'd'); System.out.println(word2); var builder = new StringBuilder("rock"); builder.replace(0, 1, "d"); System.out.println(builder); } } The example demonstrates the main difference between String and StringBuilder.
🌐
SoftwareTestingo
softwaretestingo.com › home › java › java tutorial › stringbuilder class in java with examples
StringBuilder Class In Java with Examples [ 2026 ]
January 5, 2024 - If synchronization is needed for multiple threads, it is recommended to use StringBuffer. StringBuilder is not thread-safe but performs well compared to StringBuffer. In this tutorial, we will use examples to learn about the StringBuilder class and its methods like append, reverse, delete, and toString.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › lang › class-use › StringBuilder.html
Uses of Class java.lang.StringBuilder (Java SE 11 & JDK 11 )
January 20, 2026 - Report a bug or suggest an enhancement For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String
String - JavaScript | MDN
May 22, 2026 - Although most JavaScript built-in methods handle them correctly because they all work based on UTF-16 code units, lone surrogates are often not valid values when interacting with other systems — for example, encodeURI() will throw a URIError for lone surrogates, because URI encoding uses UTF-8 encoding, which does not have any encoding for lone surrogates.
🌐
Guvi
ftp.guvi.in › hub › java-tutorial › stringbuilder-class
Java StringBuilder Class: Mutable Strings & Key Methods
Learn Java StringBuilder for fast, non-synchronized mutable strings with examples of append, replace, and reverse methods.
🌐
Reddit
reddit.com › r/javahelp › question about stringbuilder
r/javahelp on Reddit: Question about StringBuilder
June 22, 2024 -

So I get that StringBuilders are more efficient than concatenating strings with the "+" operator, because they are manipulating the underlying char[] array. But here's what I don't understand.

Let's look at case 1, where we are appending a string to the StringBuilder inside the parentheses. Doesn't this mean that for every time we call this statement, a new string has to be created and then appended to the StringBuilder?

StringBuilder().append("my new string"); // "my new string" needs to be created every time!

Now let's look at case 2, where we create a premade string, and then we append it to the StringBuilder. Wouldn't this be more efficient, because we can loop through the append statement as many times as we want without creating a new String?

String myString = "hello world";

StringBuilder.append(myString); // myString is already created!

Hope this makes sense. Asking because I'm writing a program that will potentially need to do this same operation millions of times per day, and want to get a better understanding.