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 Answer from mrhamster on reddit.com
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › StringBuilder.html
StringBuilder (Java Platform SE 8 )
April 21, 2026 - java.lang.StringBuilder · All Implemented Interfaces: Serializable, Appendable, CharSequence · public final class StringBuilder extends Object implements Serializable, CharSequence · A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-class-in-java-with-examples
StringBuilder Class in Java - GeeksforGeeks
In Java, the StringBuilder class (part of the java.lang package) provides a mutable sequence of characters.
Published   May 8, 2026
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
Why would you use a StringBuilder method over a String in Java? - Stack Overflow
What are the benefits of using a StringBuilder method over a String? Why not just amend the content within a String? I understand that a StringBuilder is mutable, but if you have to write more line... More on stackoverflow.com
🌐 stackoverflow.com
Stringbuilder vs. String - why use String builder
A String in java is immutable. Basically when you do + using String it just creates another string and stores it in memory. In loops that can quickly get out of control. Stringbuilder concatenation does not have that problem. Hope my explanation was good. More on reddit.com
🌐 r/learnjava
10
7
March 7, 2018
Am I using StringBuilder in the right way to optimise performance of a Java application?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
3
2
April 12, 2022
People also ask

What are the different constructors of StringBuilder?
There are four constructors for the Java StringBuilder class. StringBuilder(): This constructor creates an empty string builder object with no characters inside it with an initial capacity of 16. StringBuilder(CharSequence seq): This type of constructor creates a string builder object with the specified sequence of characters as the initial value. StringBuilder(int capacity): This specific constructor creates an empty string builder object with the specified capacity as the initial capacity. StringBuilder(String str): This string constructor creates a string builder object with the specified s
🌐
simplilearn.com
simplilearn.com › home › resources › software development › stringbuilder in java: constructors, methods, and examples
Stringbuilder in Java: Constructors, Methods, and Examples [Updated]
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 is the string builder in Java?
StringBuilder is a class in the Java API that provides a mutable sequence of characters. It is used for dynamic string manipulation, such as building strings from many smaller strings or appending new characters to an existing string. Additionally, it is more efficient than using the "+" operator for string concatenation, as this creates a unique string every time.  And added to this, Java String builder is a powerful tool for constructing strings. The builder can build strings of any length, from a single character to many characters. The builder is also thread-safe to be used in multi-thread
🌐
simplilearn.com
simplilearn.com › home › resources › software development › stringbuilder in java: constructors, methods, and examples
Stringbuilder in Java: Constructors, Methods, and Examples [Updated]
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.stringbuilder
StringBuilder Class (System.Text) | Microsoft Learn
sb.Insert(0, "Alphabet: "); // Replace all lowercase k's with uppercase K's. sb.Replace('k', 'K'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); } } // ...
🌐
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?

🌐
Medium
medium.com › @YodgorbekKomilo › mastering-javas-stringbuilder-the-ultimate-guide-for-beginners-8a579eb6d1f6
💡 Mastering Java’s StringBuilder: The Ultimate Guide for Beginners 🚀 | by Yodgorbek Komilov | Medium
May 9, 2025 - StringBuilder sb = new StringBuilder("race"); sb.append("car"); System.out.println(sb); // racecar sb.reverse(); System.out.println(sb); // racecar (palindrome!) Let’s solve a coding problem — print even and odd-indexed characters of a string separately: import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); scanner.nextLine(); // Consume newline for (int i = 0; i < t; i++) { String s = scanner.nextLine(); StringBuilder even = new StringBuilder(); StringBuilder odd = new StringBuilder(); for (int j = 0; j < s.length(); j++) { if (j % 2 == 0) { even.append(s.charAt(j)); } else { odd.append(s.charAt(j)); } } System.out.println(even + " " + odd); } scanner.close(); } }
Find elsewhere
🌐
The Knowledge Academy
theknowledgeacademy.com › blog › stringbuilder-java
StringBuilder in Java: Constructors, Methods, and Examples
January 1, 2009 - Strings in Java, once declared, are immutable, and changes like appending, deleting and replacing cannot be made to the object that has been declared. StringBuilder in Java allows you to make changes to strings in real-time.
🌐
IONOS
ionos.com › digital guide › websites › web development › java stringbuilder
How to use Java’s StringBuilder - IONOS
January 3, 2025 - Java’s String­Builder has 4 con­struc­tors that help convert the string into the right format for the class. They are also used for con­fig­u­ra­tion. Here are the four con­struc­tors and their purposes: StringBuilder(): Generates an empty String­Builder with a maximum capacity of 16 char­ac­ters
🌐
GitHub
github.com › openjdk-mirror › jdk7u-jdk › blob › master › src › share › classes › java › lang › StringBuilder.java
jdk7u-jdk/src/share/classes/java/lang/StringBuilder.java at master · openjdk-mirror/jdk7u-jdk
* @see java.lang.String · * @since 1.5 · */ public final class StringBuilder · extends AbstractStringBuilder · implements java.io.Serializable, CharSequence · { · /** use serialVersionUID for interoperability */ static final long serialVersionUID = 4383685877147921099L; ·
Author   openjdk-mirror
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
🌐
Baeldung
baeldung.com › home › java › java string › stringbuilder vs stringbuffer in java
StringBuilder and StringBuffer in Java | Baeldung
January 8, 2024 - Simply put, StringBuilder was introduced in Java 1.5 as a replacement for StringBuffer.
🌐
Codecademy
codecademy.com › docs › java › stringbuilder
Java | StringBuilder | Codecademy
April 24, 2025 - In Java, the StringBuilder class is a part of the java.lang package that creates a mutable sequence of characters. Unlike String objects, which are immutable, StringBuilder allows modifying character sequences without creating new objects for ...
🌐
Oracle
docs.oracle.com › en › java › javase › 20 › docs › api › java.base › java › lang › StringBuilder.html
StringBuilder (Java SE 20 & JDK 20)
July 10, 2023 - 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.
🌐
Medium
medium.com › @AlexanderObregon › javas-stringbuilder-append-method-explained-500b2ef84ec0
Java’s StringBuilder.append() Method Explained | Medium
August 6, 2024 - The StringBuilder.append() method is an essential tool for efficient string manipulation in Java. By understanding its mechanics, performance benefits over traditional string concatenation, and typical use cases, you can improve the efficiency and readability of your code.
🌐
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.
🌐
FavTutor
favtutor.com › blogs › java-stringbuilder
StringBuilder Class in Java (with Codes)
November 16, 2023 - The StringBuilder class in Java is a versatile tool for dynamically manipulating sequences of characters. Unlike the immutable nature of the String class, StringBuilder provides mutability, allowing for efficient modifications to the character ...
🌐
Hyperskill
hyperskill.org › university › java › java-stringbuilder
Java StringBuilder
December 4, 2024 - Strings in Java are immutable which means that once created, a string cannot be changed. If we want to modify the content of a string object, we should create a new string. This may not be the best way when we perform a lot of modifications because each operation creates a new object, which is bad for performance. Fortunately, there is a special class named StringBuilder that is used to create mutable string objects.
🌐
W3Schools
w3schools.com › java › java_strings.asp
Java Strings
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Baeldung
baeldung.com › home › java › java string › clearing a stringbuilder or stringbuffer
Clearing a StringBuilder or StringBuffer | Baeldung
January 27, 2024 - The method setLength updates the inner length of the StringBuilder. All entries after the length are then ignored when manipulating the StringBuilder.
🌐
Codecademy
codecademy.com › docs › java › stringbuilder › .insert()
Java | StringBuilder | .insert() | Codecademy
August 22, 2022 - The .insert() method places a sequence of characters into the StringBuilder and returns a reference to the object. ... 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.