What is the difference between String and StringBuffer in Java?

Praveen picture Praveen · Mar 13, 2010 · Viewed 181.4k times · Source

What is the difference between String and StringBuffer in Java?

Is there a maximum size for String?

Answer

Vivin Paliath picture Vivin Paliath · Mar 13, 2010

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.