StringBuilder & concatenation
Why building a string in a loop with + allocates every iteration.
Before you start
Java strings are **immutable** — once created, they cannot change. So s = s + "x" doesn't add "x" to s; it builds a whole new string containing the old text plus "x", and points s at that.
Inside a loop, that means every iteration allocates a fresh string and abandons the previous one to garbage. For 1000 iterations, that's 1000 wasted objects and hundreds of thousands of copied characters.
StringBuilder is a mutable buffer meant exactly for this. This lesson watches the difference: one shared buffer that appends in place, versus a string of one-shot allocations getting abandoned as garbage.
Stack
references to heap objectsHeap
strings are immutable; StringBuilder is notStrings are immutable. Every change creates a new object.
Step 1 of 6. result starts as an empty string. `String result = ""` creates a String object on the heap. Strings in Java are immutable — once created, their contents never change. So `result + i` does not modify this object. It creates a new one.
Step 01 / 06
result starts as an empty string
String result = "" creates a String object on the heap. Strings in Java are immutable — once created, their contents never change.
So result + i does not modify this object. It creates a new one.
public class Main { public static void main(String[] args) { // Bad: loop with + creates a new String each time String result = ""; for (int i = 0; i < 3; i++) { result = result + i; // new object every iteration } // Good: StringBuilder mutates one buffer StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.append(i); // same object, grows the buffer } String answer = sb.toString(); }}