What is the difference between String, StringBuilder, and StringBuffer in Java?
Key Differences Among String, StringBuilder, and StringBuffer in Java
Mutability:
String: Immutable. Any modification results in the creation of a new String object.
StringBuilder: Mutable. Changes are made in place without creating a new object.
StringBuffer: Mutable. Similar to StringBuilder, but thread-safe.
Thread Safety:
String: Immutable and inherently thread-safe.
StringBuilder: Not thread-safe. Should be used when no synchronization is required.
StringBuffer: Thread-safe. It synchronizes its methods to make it safe for multi-threaded environments.
Performance:
String: Slower for frequent modifications because it creates new objects.
StringBuilder: Faster than StringBuffer because it is not synchronized.
StringBuffer: Slower than StringBuilder due to method synchronization.
Usage Scenarios:
String: When the text is constant or rarely modified.
StringBuilder: When performance matters, and thread-safety is not a concern.
StringBuffer: When working in a multi-threaded environment and thread-safety is essential.