A String is carved in stone
In Java a String can never change after it's made – it is immutable. So s = s + "x" does not add to s. It builds a brand new String, copying every old character, and throws the old one away.
Think of it like this: Writing a letter on a stone tablet. To add one word you must carve a whole new tablet, copying every word from the old one first. A
StringBuilderis a notebook in pencil: you just keep writing.
Let's count how many characters get copied when we build a 1,000-letter text both ways:
public class Main {
public static void main(String[] args) {
int n = 1000;
// Way 1: String += (each step copies the whole text so far)
long copied = 0;
String s = "";
for (int i = 0; i < n; i++) {
copied += s.length();
s = s + "a";
}
System.out.println("String += copied about " + copied + " characters");
// Way 2: StringBuilder (adds at the end, like an ArrayList)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append('a');
}
String t = sb.toString();
System.out.println("StringBuilder made " + t.length() + " characters, no big copies");
System.out.println(s.equals(t));
}
}Output
String += copied about 499500 characters StringBuilder made 1000 characters, no big copies true
Half a million copies versus none. With += the work is about n²/2: O(n²). StringBuilder grows like the list you built in Module 2, so it is O(n).
Handy StringBuilder methods
| Method | Does |
|---|---|
sb.append(x) | add text, a char or a number at the end |
sb.reverse() | flip the text |
sb.insert(0, x) | add at the front (O(n), everything shifts) |
sb.setCharAt(i, c) | change one character |
sb.toString() | turn it into a normal String |
Common mistake: Comparing Strings with
==. It checks whether they are the same object, not the same text. Always usea.equals(b).