← Back to Week 2 Hub

String Immutability & StringBuilder

Why Strings create new objects, and how StringBuilder avoids that • Workbook 2a, p.26-27

Code
String greeting = "Hello"; greeting = greeting + " World"; greeting = greeting.toUpperCase();
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 = new StringBuilder("Hello"); sb.append(" World"); String result = sb.toString();
Click Step to see how StringBuilder works differently from String.
Heap Memory
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 = new StringBuilder();
for (int i = 0; i < items.length; i++) {
  sb.append(items[i]).append("\n");
}
Objects created: 0
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

← String Methods Explorer String Parsing: indexOf & substring →