Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between String and StringBuffer in Java?

What is the difference between String and StringBuffer in Java?

Is there a maximum size for String?

like image 363
Praveen Avatar asked Mar 13 '10 17:03

Praveen


People also ask

What is the difference between String and StringBuffer and StringBuilder in Java?

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.

Which is better String or StringBuffer?

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.

Is StringBuffer immutable?

Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable.


1 Answers

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.

like image 196
Vivin Paliath Avatar answered Sep 27 '22 18:09

Vivin Paliath