StringBuilder

Description

StringBuilder was introduced in Java 5. It is similar to StringBuffer, but it is not synchronized, which means it is not thread-safe. This lack of synchronization makes StringBuilder generally faster than StringBuffer but not suitable for concurrent use in multithreaded environments.

StringBuilder class in Java are mutable and designed for string manipulation. They provide methods to modify the contents of the string without creating new string objects, which can lead to better performance compared to using regular String objects for string manipulation.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
String result = sb.toString(); // result is "Hello World"

Methods Available in StringBuilder

Method

Description

Example

Output

append(String s)

Adds s at the end of the current StringBuilder

sb.append("Hello")

"Hello"

insert(int offset, String s)

Inserts s at the given index offset

sb.insert(1, "abc") (on "xyz")

"xabcyz"

replace(int start, int end, String s)

Replaces characters between start and end with s

sb.replace(1, 3, "abc") (on "xyz")

"xabcz"

delete(int start, int end)

Removes characters between start and end

sb.delete(1, 3) (on "Hello")

"Ho"

deleteCharAt(int index)

Removes the character at index

sb.deleteCharAt(2) (on "Hello")

"Helo"

reverse()

Reverses the StringBuilder content

sb.reverse() (on "abc")

"cba"

length()

Returns the number of characters in StringBuilder

sb.length() (on "Hello")

5

charAt(int index)

Returns the character at index

sb.charAt(1) (on "Hello")

'e'

setCharAt(int index, char ch)

Modifies the character at index

sb.setCharAt(1, 'A') (on "Hello")

"HAllo"

substring(int start)

Returns substring from start to end

sb.substring(1) (on "Hello")

"ello"

substring(int start, int end)

Returns substring from start to end-1

sb.substring(1, 3) (on "Hello")

"el"

toString()

Converts StringBuilder to a String

sb.toString() (on "Hello")

"Hello"

capacity()

Returns current capacity of StringBuilder

sb.capacity()

Default: 16, expands dynamically

ensureCapacity(int minCapacity)

Ensures at least minCapacity, expanding if needed

sb.ensureCapacity(50)

Capacity grows if < 50

trimToSize()

Reduces the capacity to match the length

sb.trimToSize()

Capacity reduces

Internal Working

Internally it uses a resizable array to store the characters of the string. When we append or modify the contents of the string using methods like append(), insert(), delete(), etc., they directly modify the internal character array of the object without creating new string objects. This allows for efficient string manipulation, especially when dealing with large strings or performing many concatenation operations.

Not Using String Pool

Unlike regular String objects, StringBuilder do not use the string pool for storing string literals. When we create a StringBuilder object and append or modify its contents, new character arrays may be created dynamically to accommodate the changes, but these arrays are not stored in the string pool. This behavior is different from regular String objects, which may use the string pool for storing string literals to optimize memory usage.

Using String (Concatenation) vs Using StringBuilder

Issue with using String

String joinWords(String[] words) {
    String sentence = "";  // Starts with an empty string
    for (String w: words) {
        sentence = sentence + w;  // Creates a new String object in every iteration
    }
    return sentence;
}

What's happening internally?

  • Since String is immutable, sentence = sentence + w; creates a new String object each time.

  • Suppose we have n words, the number of String objects created will be O(n).

  • But since Java needs to copy the previous string content each time, the total character copies performed sum up to O(n²).

Why StringBuilder is Better?

String joinWords(String[] words) {
    StringBuilder sentence = new StringBuilder();  // Mutable, resizable buffer
    for (String w: words) {
        sentence.append(w);  // Efficiently appends to the same object
    }
    return sentence.toString();
}

How StringBuilder improves performance

  • StringBuilder uses an internal character array and grows dynamically.

  • Instead of creating new objects, it modifies the same array.

  • Appending is O(1) amortized, so the total complexity is O(n) instead of O(n²).

Last updated

Was this helpful?