Java StringBuilder Class

Beginner
9 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition and Usage

In Java, java.lang.StringBuilder (added in Java 1.5) is a final class that stores a mutable sequence of characters. Because a String is immutable, every edit on a String creates a brand-new object. A StringBuilder lets you append(), insert(), delete(), replace(), and reverse() characters right inside one resizable buffer.

It lives in java.lang, so no import is needed, and it implements Serializable, CharSequence, and (since Java 11) Comparable<StringBuilder>. When you finish building text, call toString() to get an immutable String. Browse every guide on the StringBuilder Methods index.

Why loops prefer StringBuilder.

Writing s += item inside a loop can copy the entire string on every iteration. Calling sb.append(item) inside a loop writes into one growing buffer, and mutating methods return this so calls like sb.append("a").append(1) chain cleanly on one line.

Constructors and Basic Syntax

Create a builder empty, with a starting capacity, or from existing text:

Java
StringBuilder a = new StringBuilder();          // empty, initial capacity 16
StringBuilder b = new StringBuilder(128);       // empty, initial capacity 128
StringBuilder c = new StringBuilder("Hello");   // text "Hello", capacity 5 + 16 = 21

c.append(", Java").insert(5, "!").reverse();    // chaining works (returns this)
String text = c.toString();                     // convert to immutable String

StringBuilder vs StringBuffer vs String

Choose the class that matches whether the text changes and whether multiple threads share it:

ClassMutable?Thread-safe?When to use
StringNo (immutable)Yes (immutable)Fixed text, constants, map keys, and final return values
StringBuilderYesNoDefault choice for building or editing text in loops or one thread
StringBufferYesYes (synchronized)Legacy or shared multi-thread buffer; slower in single-threaded code due to locking

Capacity vs Length

length() counts how many UTF-16 char units are currently in the builder. capacity() reports how many slots its internal array holds before it must allocate a bigger array. An empty new StringBuilder() starts with capacity 16, and new StringBuilder(str) starts with str.length() + 16. When text outgrows capacity, the buffer grows automatically (typically to 2 * oldCapacity + 2 in OpenJDK, though the exact formula is an implementation detail). Use ensureCapacity() before huge appends or trimToSize() afterward to manage memory.

Common Pitfalls

MistakeWhat goes wrongWhat to do instead
sb1.equals(sb2)Checks object identity (==), not text contentCompare sb1.toString().equals(sb2.toString()) (or compareTo == 0 in Java 11+)
Forgetting toString()Passing StringBuilder where a String parameter is required fails to compileCall sb.toString() when done building
Leaving a trailing commaLooping with sb.append(x).append(",") leaves an extra comma at the endTrim with sb.setLength(sb.length() - 1) or deleteCharAt() when sb.length() > 0
Chaining after setCharAtsetCharAt() and setLength() return void, not thisCall them as standalone statements, not inside a chain

Java Examples

Example 1 — Build a CSV Line in a Loop and Chain Calls

Append items in a loop without creating temporary String objects on every step, trim the trailing comma, and chain a summary onto the same builder.

Java
public class StringBuilderHubLoop {
    public static void main(String[] args) {
        String[] items = {"pen", "notebook", "eraser"};
        StringBuilder sb = new StringBuilder();

        for (String item : items) {
            sb.append(item).append(", ");
        }
        if (sb.length() >= 2) {
            sb.setLength(sb.length() - 2);
        }
        sb.insert(0, "Cart: ").append(" (").append(items.length).append(" items)");

        String summary = sb.toString();
        System.out.println(summary);
    }
}

How It Works

  1. One buffer in the loop. Each iteration chains two append calls on the same StringBuilder instead of allocating a new String with +=.
  2. Trim the trailing separator. After the loop ends with ", ", setLength(sb.length() - 2) cuts off the final two characters in place.
  3. Chain and freeze. insert(0, "Cart: ") prepends a prefix and append adds the count; toString() returns the final immutable String.

Example 2 — Insert, Replace, Delete, and Check a Palindrome

Modify text directly inside one buffer, then reverse a word in a temporary builder to test whether it reads the same backward.

Java
public class StringBuilderHubEdit {
    public static void main(String[] args) {
        StringBuilder code = new StringBuilder("order-1234-temp");
        code.replace(0, 5, "INV");
        code.delete(code.indexOf("-temp"), code.length());
        code.setCharAt(3, ':');
        System.out.println("Edited: " + code);

        String word = "radar";
        boolean isPalindrome = word.equals(new StringBuilder(word).reverse().toString());
        System.out.println(word + " palindrome? " + isPalindrome);
    }
}

How It Works

  1. Replace and delete in place. replace(0, 5, "INV") swaps "order" for a shorter word, and delete removes everything from "-temp" to the end.
  2. Single-char edit. setCharAt(3, ':') changes the hyphen at index 3 to a colon (remembering that setCharAt returns void).
  3. One-line palindrome test. Wrapping word in a new StringBuilder, reversing it, and calling toString() produces a reversed String for equals().

Example 3 — Initial Capacity, Growth, and Comparing Content Safely

Inspect default and custom initial capacities, see why sb1.equals(sb2) returns false, and compare content with toString().equals(...).

Java
public class StringBuilderHubCompare {
    public static void main(String[] args) {
        StringBuilder empty = new StringBuilder();
        StringBuilder fromText = new StringBuilder("Java");
        System.out.println("empty capacity: " + empty.capacity() + ", length: " + empty.length());
        System.out.println("fromText capacity: " + fromText.capacity() + ", length: " + fromText.length());

        StringBuilder a = new StringBuilder("CodeToFun");
        StringBuilder b = new StringBuilder("CodeToFun");
        System.out.println("a.equals(b): " + a.equals(b));
        System.out.println("text equals: " + a.toString().equals(b.toString()));
    }
}

How It Works

  1. Initial buffer sizes. An empty builder starts with capacity 16, while new StringBuilder("Java") starts with 4 + 16 = 20 slots.
  2. Identity-based equals(). StringBuilder does not override Object.equals, so a.equals(b) compares references and prints false even for identical text.
  3. Compare as Strings. Converting both builders with toString() and calling String.equals compares the actual characters and returns true.

Next: Java StringBuilder Methods by Group

Full list with short descriptions: Java StringBuilder Methods index.

Frequently Asked Questions

java.lang.StringBuilder is a final, mutable sequence of characters introduced in Java 1.5. Unlike String, you can append, insert, delete, replace, and reverse characters inside the same object without creating a new String on every edit.
Strings are immutable, so repeating result += piece inside a loop can copy all accumulated characters into a brand-new String each step. Appending to a StringBuilder writes into one resizable char buffer and avoids that repeated copying.
String is immutable. StringBuilder and StringBuffer are both mutable with the same methods, except StringBuffer methods are synchronized for thread safety and therefore slightly slower in single-threaded code.
StringBuilder inherits Object.equals, which checks whether two references point to the exact same object. Compare content with sb1.toString().equals(sb2.toString()) (or sb1.compareTo(sb2) == 0 on Java 11+).
length() is how many char units are currently stored in the builder. capacity() is how many char units its internal array can hold before allocating a larger buffer.

Browse every StringBuilder method

Open the methods index for categorized guides with examples and FAQs.

StringBuilder Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful