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
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › StringBuilder.html
StringBuilder (Java Platform SE 8 )
April 21, 2026 - The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.
🌐
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
People also ask

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
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
🌐
IONOS
ionos.com › digital guide › websites › web development › java stringbuilder
How to use Java’s StringBuilder - IONOS
January 3, 2025 - The append() method is used to add one string to another. It has various pa­ra­me­ters. Here’s how it works in practice: public class Main { public static void main(String[] argv) throws Exception { StringBuilder str = new StringBuilder("ABCDE"); str.append("FGHIJK"); System.out.println(str); } }java ·
🌐
Tutorialspoint
tutorialspoint.com › java › lang › java_lang_stringbuilder.htm
Java StringBuilder Class
package com.tutorialspoint; public class StringBuilderDemo { public static void main(String[] args) { StringBuilder stringBuilder = new StringBuilder("tuts "); System.out.println("builder = " + stringBuilder); // appends the boolean argument as string to the string stringBuilder stringBuilder.append(true); // print the string stringBuilder after appending System.out.println("After append = " + stringBuilder); stringBuilder = new StringBuilder("abcd "); System.out.println("stringBuilder = " + stringBuilder); // appends the boolean argument as string to the string stringBuilder stringBuilder.append(false); // print the string stringBuilder after appending System.out.println("After append = " + stringBuilder); } }
🌐
Hyperskill
hyperskill.org › university › java › java-stringbuilder
Java StringBuilder
December 4, 2024 - StringBuilder append(String str) concatenates the given string to the end of the invoking StringBuilder object. There are also several overloaded versions of this method to take primitive types and even arrays of characters.
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.
🌐
The Knowledge Academy
theknowledgeacademy.com › blog › stringbuilder-java
StringBuilder in Java: Constructors, Methods, and Examples
January 1, 2009 - Once you have a StringBuilder object, you can use various methods to manipulate its string. Unlike the immutable String class, the StringBuilder class is mutable, which means you can modify its contents without creating a new object. Boost your knowledge of Java by learning more about Constructors in Java.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › lang › StringBuilder.html
StringBuilder (Java SE 17 & JDK 17)
April 21, 2026 - The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.
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?
🌐
Simplilearn
simplilearn.com › home › resources › software development › stringbuilder in java: constructors, methods, and examples
Stringbuilder in Java: Constructors, Methods, and Examples [Updated]
3 weeks ago - StringBuilder in Java is used to create mutable (modifiable) string. Learn all about it, important methods and constructors, and more now. Start learning!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Codecademy
codecademy.com › docs › java › stringbuilder
Java | StringBuilder | Codecademy
April 24, 2025 - This example demonstrates the main operations you can perform with StringBuilder including append, insert, replace, delete, and reverse methods.
🌐
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?

🌐
Great Learning
mygreatlearning.com › blog › it/software development › java stringbuilder class: methods, examples and more
Java StringBuilder Class: Methods, Examples and more
September 12, 2024 - In this example, the ensureCapacity() method is used to ensure that the capacity of the string is minimum before we perform more operations on that string. It is essential to know the capacity of the string before performing any operation. ... Learn Java the right way! Our course teaches you essential programming skills, from coding basics to complex projects, setting you up for success in the tech industry. ... This is all about the Java StringBuilder class, where we have seen the methods that can be used in this class.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › class-use › StringBuilder.html
Uses of Class java.lang.StringBuilder (Java Platform SE 8 )
March 16, 2026 - Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
🌐
Scaler
scaler.com › home › topics › java › stringbuilder in java with examples, methods and constructors
StringBuilder in Java with Examples, Methods, and Constructors - Scaler Topics
May 3, 2023 - This method returns the first index of the text if it is present in the StringBuilder sequence, otherwise returns -1. Let's understand how to search the text in the StringBuilder object using an example. ... The world is present in the StringBuilder sequence at the starting index 11 but the text "ScalerZ" is not present in the StringBuilder sequence that's why -1 will return. Use this Java Compiler to compile your code.
🌐
Coderanch
coderanch.com › t › 594164 › java › Stringbuilder
Problem with Stringbuilder (Beginning Java forum at Coderanch)
October 2, 2012 - They're two completely separate, unrelated, independent variables that pointed to the same object when the method was called, but by setting sb to null inside the method, we're just saying that this particular variable now does not point to any object--we're not affecting the caller's variable, ...
🌐
Maven Repository
mvnrepository.com › artifact › org.apache.commons › commons-lang3
Maven Repository: org.apache.commons » commons-lang3
November 12, 2025 - Apache Commons Lang, a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so standard as to justify existence in java.lang. The code is tested using the latest revision of the JDK for supported LTS releases: 8, 11, 17, 21 and 25 currently ...