What is the difference between String and StringBuffer in Java?
Is there a maximum size for String?
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.
The StringBuffer class is used to represent characters that can be modified. The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations.
Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable.
String
is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer
is used to represent characters that can be modified.
Performance wise, StringBuffer
is faster when performing concatenations. This is because when you concatenate a String
, you are creating a new object (internally) every time since String
is immutable.
You can also use StringBuilder
which is similar to StringBuffer
except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE
(231 - 1 = 2,147,483,647) or maximum heap size divided by 2 (see How many characters can a Java String have?). More information here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With