If you don't have the memory to create a new StringBuilder, then you don't have the memory to create a new StringBuilder, and cloning wouldn't change that. The only real way to copy a StringBuilder is new StringBuilder(myBuilder), or something equivalent.

If you're getting OutOfMemoryException, you'll need to either get more memory, or find some other way to reduce memory consumption.

Answer from Louis Wasserman on Stack Overflow
Top answer
1 of 3
13

I'd just like to make a slight change to the code. When you are instantiating a StringBuilder, you have the opportunity to specify the capacity of it. Using this constructor, we can avoid having it resized more than necessary.

public String frontTimes(String str, int n) {
    StringBuilder stringBuilder = new StringBuilder(3 * n);
    if (str.length() > 3) {
        str = str.substring(0, 3);
    }
    for (int i = 0; i < n; i++) {
        stringBuilder.append(str);
    }
    return stringBuilder.toString();
}

Note how many times that 3 is declared? Would be better to extract that to a constant, or even better, a parameter. And with a few other changes to the above (as suggested by @rolfl in chat):

public String frontTimes(final String str, final int frontLength, final int times) {
    String copyString = str.length() > frontLength ? str.substring(0, frontLength) : str;
    StringBuilder stringBuilder = new StringBuilder(copyString.length() * times);
    for (int i = 0; i < times; i++) {
        stringBuilder.append(copyString);
    }
    return stringBuilder.toString();
}
2 of 3
10

I am a fan of using primitives. In this case, the performance benefit would be minimal, but the number of copies would actually be less.....

In reality, I would probably use the StringBuilder approach similar to what other answers have given (+1 to them all), but you should be aware that the following code is likely faster, has fewer iterations through the loop, and will scale better..... if you ever need to make millions of copies... ;-) (now here with a cheesy test case in ideone too)

/**
 * Using the input source string, duplicate its prefix the specified count
 * times.
 * @param source       The source string containing the prefix
 * @param prefixLength The length of the prefix to use (or the whole string
 *                     if the prefix is larger than the String)
 * @param count        the number of times to repeat the prefix.
 * @return the resulting duplicated string, or an empty string if the source
 *         is invalid or the count or prefix length is zero
 */
public static String duplicatePrefix(final String source, final int prefixLength, final int count) {
    if (source == null || source.length() == 0 || prefixLength <= 0 || count <= 0) {
        return "";
    }

    final int actual = Math.min(source.length(), prefixLength);
    final int size = actual * count;
    final char[] results = new char[size];
    // copy the first prefix to the output
    source.getChars(0, actual, results, 0);
    // duplicate the previously populated chars as often as needed.
    int currentpos = actual;
    while (currentpos < size) {
        // copy as much as you can, limited by the available space to copy to.
        System.arraycopy(results, 0, results, currentpos, Math.min(currentpos, size - currentpos));
        // double the current position
        currentpos <<= 1;
    }
    return new String(results);
}

Note that the loop in the above code will iterate only \ times where, which can be a significant saving in the event that count is large, though the ArrayCopy is still an \ operation, so it is a toss up as to whether it will improve the speed at all... it will need some benchmarking.

Discussions

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
java - How to copy a String substring to a StringBuilder - Stack Overflow
Perhaps the implementation has changed from whatever version you're looking at, but currently StringBuilder#append(CharSequence,int,int) attempts to use arraycopy when the first argument is an instance of Sting. See github.com/openjdk/jdk/blob/master/src/java.base/share/classes/… More on stackoverflow.com
🌐 stackoverflow.com
Convert the string into stringBuilder in java - Stack Overflow
Also note that StringBuffer and StringBuilder are two (similar but) different classes in Java. More on stackoverflow.com
🌐 stackoverflow.com
java - How to get character array which is inside StringBuilder to avoid array copy - Stack Overflow
@ThomasJungblut, You can not make a proxy class in any package that start from java due to its restriction build in default class loader. You will get a securiry exception 2013-12-11T11:21:08.97Z+00:00 ... Save this answer. ... Show activity on this post. ... CopyField stringbuilderCharField = ... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Can StringBuilder Be Serialized?
A: StringBuilder implements Serializable, allowing its instances to be serialized and deserialized, though caution is needed with mutable data.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › stringbuilder class in java
StringBuilder Class in Java: A Complete Guide with Examples
Can StringBuilder Be Used with Streams?
A: StringBuilder isn't directly compatible with Java Streams but can be used within stream operations for efficient string concatenation.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › stringbuilder class in java
StringBuilder Class in Java: A Complete Guide with Examples
How Does StringBuilder Handle Null Arguments?
A: Passing null to StringBuilder's methods may cause a NullPointerException, depending on the method's implementation.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › stringbuilder class in java
StringBuilder Class in Java: A Complete Guide with Examples
🌐
Delft Stack
delftstack.com › home › howto › java › java string copy
How to Copy a String in Java | Delft Stack
February 2, 2024 - A StringBuilder is then initialized with the original String as its argument. The toString method is subsequently applied to the StringBuilder instance, creating a new String named copy that effectively duplicates the content of the original string.
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-class-in-java-with-examples
StringBuilder Class in Java - GeeksforGeeks
StringBuilder is a mutable sequence of characters provided by the java.lang package. Unlike String, its contents can be modified without creating a new object for every operation.
Published: September 1, 2026
🌐
Baeldung
baeldung.com › home › java › java string › how to convert string to stringbuilder and vice versa in java
How to Convert String to StringBuilder and Vice Versa in Java | Baeldung
April 7, 2025 - Understanding how to convert between String and StringBuilder is essential for efficient String handling. In this quick tutorial, we’ll explore how to perform these conversions effectively. In Java, Strings are immutable, meaning once an object is created, it cannot be changed.
🌐
Reddit
reddit.com › r/learnjava › what happens when i use tostring() method on a stringbuilder?
r/learnjava on Reddit: What happens when i use toString() method on a StringBuilder?
June 30, 2020 -

So let's say i have a code like this:-

StringBuilder str = new StringBuilder("hello");
System.out.println(str.toString());    

So is it like there are two arrays, StringBuilder and String and we loop StringBuilder and copy it's contents character by character into the String? What would be the time complexity of this process?

Find elsewhere
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › stringbuilder class in java
StringBuilder Class in Java: A Complete Guide with Examples
March 5, 2025 - This approach reduces unnecessary memory reallocations and enhances performance. Example: Setting Initial Capacity · StringBuilder sb = new StringBuilder(50); System.out.println("Initial capacity: " + sb.capacity()); Copied!
🌐
Baeldung
baeldung.com › home › java › java string › reuse stringbuilder for efficiency
Reuse StringBuilder for Efficiency | Baeldung
January 8, 2024 - When an application creates a new object, it will likely be allocated in a different memory location each time, leading to cache misses and reduced performance. By reusing StringBuilder instances, the same object can be used repeatedly, leading to better cache utilization and improved performance.
🌐
ZetCode
zetcode.com › java › stringbuilder
Java StringBuilder - mutable Java strings with StringBuilder
Java StringBuilder tutorial shows how to use StringBuilder in Java. Java String objects are immutable; it is only possible to create modified copies of the original string.
🌐
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 each operation.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.stringbuilder.copyto
StringBuilder.CopyTo Method (System.Text) | Microsoft Learn
September 15, 2021 - The CopyTo method is intended to be used in the rare situation when you need to efficiently copy successive sections of a StringBuilder object to an array.
🌐
Blogger
javahungry.blogspot.com › 2022 › 02 › string-to-stringbuilder.html
2 ways to Convert String to StringBuilder in Java | Java Hungry
To convert String to StringBuilder in Java you can use a StringBuilder class constructor that accepts String.
🌐
Dot Net Perls
dotnetperls.com › stringbuilder-java
Java - StringBuilder Examples - Dot Net Perls
StringBuilder speeds up concatenation by using a shared buffer. The buffer is mutable, so no copying is needed for appends. Here we import java.lang.StringBuilder. We use StringBuilder in a for-loop.
🌐
Intellimindz
intellimindz.com › string-builder-in-java
Mastering StringBuilder in Java
February 24, 2024 - In conclusion, StringBuilder in Java offers performance benefits through its mutable nature, efficient string manipulation methods, and the ability to avoid the overhead associated with string concatenation using the + operator.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.stringbuilder
StringBuilder Class (System.Text) | Microsoft Learn
Convert the StringBuilder instance to a String by calling the ToString method, then access the characters in the string. Copy the contents of the existing StringBuilder object to a new pre-sized StringBuilder object. Performance improves because ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-tostring-method-in-java-with-examples
StringBuilder toString() method in Java with Examples - GeeksforGeeks
August 18, 2026 - A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString().
🌐
IONOS UK
ionos.co.uk › digital guide › websites › web development › java stringbuilder
How to use Java’s StringBuilder - IONOS UK
January 3, 2025 - StringBuilder(String str): Creates a String­Build­er with the string you enter