Differences between String, StringBuffer, and StringBuilder in Java
In Java, String
, StringBuffer
, and StringBuilder
are all used to represent and manipulate sequences of characters, but they have some key differences in terms of their functionality, performance, and thread-safety.
String
The String
class in Java represents an immutable sequence of characters. This means that once a String
object is created, its value cannot be changed. Any operation that appears to modify a String
object actually creates a new String
object with the desired changes.
String s1 = "Hello";
s1 = s1 + ", world!"; // Creates a new String object "Hello, world!"
String
objects are thread-safe, which means they can be safely accessed by multiple threads without the need for explicit synchronization.
StringBuffer
The StringBuffer
class in Java represents a mutable sequence of characters. Unlike String
, StringBuffer
objects can be modified after they are created. StringBuffer
provides synchronized methods for thread-safe operations, making it suitable for use in multi-threaded environments.
StringBuffer sb = new StringBuffer("Hello");
sb.append(", world!"); // Modifies the existing StringBuffer object
StringBuffer
is thread-safe, which means its methods are synchronized, ensuring that only one thread can access the object at a time.
StringBuilder
The StringBuilder
class in Java is similar to StringBuffer
, but it is not thread-safe. StringBuilder
provides the same methods as StringBuffer
for modifying the sequence of characters, but it does not have the overhead of synchronization.
StringBuilder sb = new StringBuilder("Hello");
sb.append(", world!"); // Modifies the existing StringBuilder object
StringBuilder
is not thread-safe, which means its methods are not synchronized. This makes StringBuilder
more efficient than StringBuffer
in single-threaded environments, as it avoids the overhead of synchronization.
In summary, the main differences between String
, StringBuffer
, and StringBuilder
are:
- Mutability:
String
is immutable, whileStringBuffer
andStringBuilder
are mutable. - Thread-safety:
StringBuffer
is thread-safe, whileStringBuilder
is not. - Performance:
StringBuilder
is generally faster thanStringBuffer
in single-threaded environments due to the absence of synchronization overhead.
The choice between String
, StringBuffer
, and StringBuilder
depends on the specific requirements of your application, such as the need for thread-safety, the frequency of string manipulations, and the performance requirements.