Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    StringBuilder

    StringBuilder is a mutable sequence of characters: you change it in place. Call toString() at the end to get a String.

    Chapter 7 of 103 min read

    The Plain Picture#

    Instead of reprinting a whole badge every time you add one letter, you use a whiteboard: write, add, erase, insert — all on the same board. When you're finished, print the final badge once.

    The Real Names#

    • StringBuilder is a mutable sequence of characters: you change it in place. Call toString() at the end to get a String.

    • (StringBuffer is an older, thread-safe but slower version. Use StringBuilder unless you're sharing it across threads — which you almost never do.)

    Under the Hood#

    Java
    StringBuilder sb = new StringBuilder("study");
    
    sb.append("buddy").insert(0, "[").append(']'); // methods return the builder, so calls can chain
    
    System.out.println(sb); // [studybuddy]
    
    sb.reverse();
    
    System.out.println(sb); // ]yddubyduts[
    
    sb.reverse();
    
    sb.setCharAt(1, 'S');
    
    sb.deleteCharAt(sb.length() - 1);
    
    System.out.println(sb + " " + sb.length()); // [Studybuddy 11
    
    String finished = sb.toString();

    Why + in a loop is slow — measured#

    Building a 50,000-character string one character at a time:

    Java
    String slow = "";
    
    for (int i = 0; i < 50_000; i++) slow += "x"; // a NEW string every round, copying everything so far
    
    StringBuilder fast = new StringBuilder();
    
    for (int i = 0; i < 50_000; i++) fast.append("x"); // adds to the same buffer

    Real timing on this Mac:

    Output
    concat: 133 ms, builder: 0 ms, same=true

    Why: round k of the + loop copies k characters into a brand-new string, so the total work is 1 + 2 + … + n ≈ n²/2 character copies. At n = 50,000 that's over a billion. StringBuilder keeps a growable internal array (like ArrayList, Collections, From the Inside) and just adds to it, so the total is about n. In Big-O terms (Big-O and Complexity): O(n²) vs O(n). Double the input and the + version takes four times as long.

    (For a single expression like "Score: " + points + "/" + total, the compiler already optimises it; the problem is += inside loops.)

    In DSA: building output, reversing strings, constructing answers character by character in backtracking (Backtracking (coming soon)) — always StringBuilder.

    Check yourself

    3 questions
    1

    String vs StringBuilder — which is mutable?

    Show answer

    StringBuilder.

    2

    Why is result += piece inside a loop O(n²)?

    Show answer

    Each += builds a new String and copies everything so far; the copies add up to about n²/2.

    3

    How do you get a String out of a StringBuilder?

    Show answer

    sb.toString().