What is the difference between String, StringBuilder, and StringBuffer?

Beginner

Answer

  • String: Immutable, thread-safe. Each modification creates a new object.
  • StringBuilder: Mutable, not thread-safe, faster for single-threaded string operations.
  • StringBuffer: Mutable, thread-safe (synchronized), slower due to synchronization overhead.
String str = "Hello";
str += " World"; // Creates new String object
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies existing buffer