Complete Guide to Java StringBuilder with Examples & Best Practices

Introduction

In Java, StringBuilder is a mutable sequence of characters. Unlike String, which is immutable, StringBuilder allows us to modify the content of the string without creating new objects every time we update it. This makes StringBuilder ideal for scenarios where we need to perform many modifications on strings, such as in loops or intensive string manipulations.

Why StringBuilder?

  • Performance: Repeated string concatenation using String results in the creation of many temporary objects, leading to memory and CPU overhead.
  • Mutability: StringBuilder offers methods to modify the string directly, improving efficiency.
  • Use Case: It’s especially useful in scenarios like loops, building large strings, and where thread safety is not a concern (use StringBuffer if thread safety is required).

Key Features of StringBuilder

  • Mutable sequence of characters.
  • Not synchronized (faster than StringBuffer).
  • Provides methods like append(), insert(), delete(), reverse(), and replace().

How to Create a StringBuilder Object

StringBuilder sb1 = new StringBuilder(); // Creates an empty StringBuilder
StringBuilder sb2 = new StringBuilder("Initial text"); // Creates StringBuilder with initial content

Commonly Used Methods of StringBuilder

1. append()

Appends the specified string or data to the current sequence.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World

2. insert()

Inserts the specified string at the given index.

StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, ",");
System.out.println(sb.toString()); // Output: Hello, World

3. replace()

Replaces a substring with the specified string.

StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // Output: Hello Java

4. delete()

Deletes a substring between the specified indices.

StringBuilder sb = new StringBuilder("Hello Java World");
sb.delete(5, 10);
System.out.println(sb.toString()); // Output: Hello World

5. reverse()

Reverses the characters in the sequence.

StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb.toString()); // Output: olleH

6. length() and capacity()

  • length() returns the number of characters.
  • capacity() returns the allocated storage size.
StringBuilder sb = new StringBuilder();
System.out.println("Length: " + sb.length());    // 0
System.out.println("Capacity: " + sb.capacity()); // Default capacity, usually 16

Performance Comparison: String vs StringBuilder

public class PerformanceTest {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < 10000; i++) {
            str += "a";  // Inefficient due to creating new String objects each time
        }
        long endTime = System.currentTimeMillis();
        System.out.println("String concatenation time: " + (endTime - startTime) + " ms");

        startTime = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            sb.append("a");  // Efficient as it modifies the same object
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuilder append time: " + (endTime - startTime) + " ms");
    }
}

Typically, StringBuilder performs much faster.

When to Use StringBuilder vs StringBuffer vs String

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-SafeYesNoYes
PerformanceLow (for frequent modifications)HighModerate
Use CaseStatic textSingle-threaded modificationsMulti-threaded modifications

🎯Conclusion

StringBuilder is a powerful and efficient class for string manipulation in Java, particularly useful in situations where performance matters. Understanding its key methods helps in writing more efficient and cleaner code compared to using the String class for every small string modification.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *