AI Features

StringBuilder and StringBuffer

Learn to construct and manipulate mutable text sequences efficiently using StringBuilder, understand its thread-safe counterpart StringBuffer, and decide which text class to use for specific scenarios.

We discovered that Java String objects are immutable once created, they cannot be changed. While this ensures safety and security, it incurs a hidden performance cost when we frequently modify text. Every time we concatenate strings in a loop or modify a sentence, Java quietly creates entirely new objects in memory, discarding the old ones.

To solve this, Java provides powerful tools designed specifically for heavy-duty text manipulation. In this lesson, we will learn how to use StringBuilder and StringBuffer to write efficient, high-performance code that handles dynamic text with ease.

The cost of immutability

When we modify a String using the + operator, Java does not actually change the original object. Instead, it copies the existing characters, appends the new ones, and allocates memory for a brand-new object.

If we do this once or twice, the cost is negligible. However, inside a loop, this behavior can severely impact performance. Consider a scenario where we want to build a long sentence word by word.

If we use string concatenation, we flood memory with intermediate objects that are discarded immediately. This puts unnecessary pressure on the Garbage Collector, slowing down our application.

Here is how StringBuilder solves this problem by using a single, resizable container:

Java 25
public class StringPerformance {
public static void main(String[] args) {
// Inefficient: Creates a new String object in every iteration
String slowText = "";
for (int i = 0; i < 5; i++) {
slowText += i + " ";
}
System.out.println("String Result: " + slowText);
// Efficient: Modifies the same object internally
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 5; i++) {
builder.append(i).append(" ");
}
System.out.println("Builder Result: " + builder.toString());
}
}
    ...