Q8: What are the differences between String, StringBuilder, and StringBuffer?

  • String: Immutable character sequence. Modifications create new object instances.
  • StringBuilder: Mutable character sequence. Non-thread-safe, high performance.
  • StringBuffer: Mutable character sequence. Thread-safe using synchronized methods (slower overhead).
Key Takeaways
  • Use String for immutable constants.
  • Use StringBuilder for single-threaded dynamic string concatenation.
  • Use StringBuffer for multi-threaded thread-safe string concatenation.
Knowledge Check

Which class should be preferred for high-speed string concatenation in single-threaded methods?