Praveen Praveen - 4 months ago 13
Java Question

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?

Answer

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.