In this article, we will discuss the difference between String
and StringBuffer
. Both of these classes used to handle sequence of characters. However they are different in certain areas such as mutability, performance, and thread-safety. Let’s discuss these differences with examples.
String
Immutability: String
objects are immutable. This means that once a String
object is created, its value cannot be changed. If any changes are made in a String a new String
object is created.
String str1 = "Hello";
String str2 = str1.concat(", World!"); // str2 is a new String object
Performance: As we now know that String
is immutable, concatenation operations create new String
objects, this can cause significant performance overhead.
Usage: Strings are mostly used in scenarios where you do not require to change frequently.
Thread Safety: String
is inherently thread-safe because it is immutable.
StringBuffer
Mutability: StringBuffer
objects are mutable. This means when you change the value of StringBuffer
objects, it doesn’t create new objects.
StringBuffer sb = new StringBuffer("Hello");
sb.append(", World!"); // sb is modified directly
Performance: StringBuffer
is more efficient than String as any modification doesn’t create new objects. This is generally useful in scenarios where frequent changes are required.
Usage: StringBuffer
is generally useful in scenarios where frequent changes are required.
Thread Safety: StringBuffer
is thread-safe because the methods of StringBuffer class are synchronized. This makes it safe to use in multi-threaded environments.
String vs StringBuffer Example Comparison
An example to demonstrate difference in performance and usage:
Using String
public class StringExample {
public static void main(String[] args) {
String str = "Text";
for (int i = 0; i < 100; i++) {
str += " Text"; // Each iteration creates a new String object
}
System.out.println(str);
}
}
Using StringBuffer
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Text");
for (int i = 0; i < 100; i++) {
sb.append(" Text"); // Modifies the same StringBuffer object
}
System.out.println(sb.toString());
}
}
Key Points
- Memory Efficiency:
String
is less memory efficient as any change creates newString
object.StringBuffer
is more memory efficient in such scenarios. - Thread Safety:
String
andStringBuffer
are both thread-safe, however the reason for thread-safety is different in both cases.String
is thread-safe because they are immutable, whereasStringBuffer
is thread-safe because its methods are synchronized. - Usage:
- Use
String
when changes to string are not so frequent. - Use
StringBuffer
when you need to make frequent changes to the string.
- Use
Leave a Reply