String — immutable (cannot be changed). StringBuilder — mutable, fast, NOT thread-safe. StringBuffer — mutable, thread-safe, slower.
Analogy: String is like a printed book — once printed, you can't change it. To "modify" it, you print a new book. StringBuilder is like a notebook you can write in freely. StringBuffer is like a shared notebook with a lock — safe for multiple people but slower because of the locking.
String (java.lang.String):
1String s = "Hello";2s = s + " World"; // Creates a NEW String object — "Hello" is discarded34// BAD: String concatenation in a loop (O(n^2) time complexity)5String result = "";6for (int i = 0; i < 10000; i++) {7 result += i + " "; // Each += creates a new String!8}9// This creates ~10,000 temporary String objects!
StringBuilder (java.lang.StringBuilder):
1StringBuilder sb = new StringBuilder();2sb.append("Hello");3sb.append(" ");4sb.append("World");5String result = sb.toString(); // "Hello World"67// Fast: string building in a loop (O(n) time complexity)8StringBuilder sb2 = new StringBuilder(1000); // pre-size for efficiency9for (int i = 0; i < 10000; i++) {10 sb2.append(i).append(" ");11}12String result2 = sb2.toString();1314// Other useful methods:15sb.insert(5, "Beautiful "); // Insert at index16sb.delete(0, 6); // Delete range17sb.replace(0, 5, "Hi"); // Replace range18sb.reverse(); // Reverse the string19sb.charAt(0); // Access character20sb.length(); // Current length21sb.capacity(); // Current capacity
StringBuffer (java.lang.StringBuffer):
synchronized.1StringBuffer sbf = new StringBuffer();2sbf.append("Hello");3sbf.append(" World");4String result = sbf.toString(); // "Hello World"56// Thread-safe: can be shared between threads7class SharedBuilder {8 private StringBuffer buffer = new StringBuffer();910 public synchronized void addLine(String line) {11 buffer.append(line).append("\n");12 }1314 public String build() {15 return buffer.toString();16 }17}
Performance comparison:
When to use which:
Common mistakes:
+ in a loop to build strings (use StringBuilder instead).