Click Step to execute each line and watch what happens in memory.
Heap Memory
greeting➜
Objects created: 0
Key insight: Strings in Java are immutable — once created, a String object can never be changed.
Every operation that seems to "modify" a String actually creates a brand new object in memory.
The old object is abandoned and eventually garbage collected.
Code
StringBuilder sb = newStringBuilder("Hello");sb.append(" World");String result = sb.toString();
Click Step to see how StringBuilder works differently from String.
Heap Memory
StringBuilder (mutable)
sb➜
Objects created: 0
Tip: StringBuilder modifies characters in place — no new objects needed.
The internal character array grows as needed, but it is still the same object.
When you are done building, call .toString() to get a regular String.
Scenario: Building a Grocery List in a Loop
Watch what happens when we build a string with 5 items — one approach creates many objects, the other stays efficient.
String Concatenation
String list = ""; for (int i = 0; i < items.length; i++) {
list = list + items[i] + "\n";
}
Objects created: 0
StringBuilder
StringBuilder sb = newStringBuilder(); for (int i = 0; i < items.length; i++) {
sb.append(items[i]).append("\n");
}
Objects created: 0
Use StringBuilder when building a string in a loop — it saves memory and runs faster!
Tip: For simple one-line concatenations like String name = first + " " + last;, regular String is fine.
StringBuilder shines when you are building strings in loops or across many operations.
Use the tabs above to explore each concept • Click Step to advance through the animation