What is the difference between String class and StringBuffer class?
-
I'm surprised a google search provided no results? – Mitch Wheat Jul 27 '13 at 01:41
-
oops. sorry for asking this question. – siddhu99 Jul 27 '13 at 01:45
-
StringBuffer is a legacy class and String is not. Use StringBuilder if you can (as the Javadoc states) – Peter Lawrey Jul 27 '13 at 08:05
2 Answers
Strings are immutable. Their internal state cannot change. A StringBuffer allows you to slowly add to the object without creating a new String at every concatenation.
Its good practice to use the StringBUilder instead of the older StringBuffer.
A common place to use a StringBuilder or StringBuffer is in the toString method of a complicated object. Lets say you want the toString method to list elements in an internal array.
The naive method:
String list = "";
for (String element : array) {
if (list.length > 0)
list += ", ";
list += element;
}
return list;
This method will work, but every time you use a += you are creating a new String object. That's undesirable. A better way to handle this would be to employ a StringBuilder or StringBuffer.
StringBuffer list = new StringBuffer();
for (String element : array) {
if (list.length() > 0)
list.append(", ");
list.append(element);
}
return list.toString();
This way, you only create the one StringBuffer but can produce the same result.

- 1,265
- 7
- 16
-
-
1Or simply not waste your time. This is clearly a duplicate question ... multiple times over. – Stephen C Jul 27 '13 at 01:45
"String: http://docs.oracle.com/javase/tutorial/i18n/text/characterClass.html
String buffer: http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
Job done. Google is your friend
When you say string bufefer, you shoudl probably look into stringbuilder instead.
You can append to them to make 'new' strings.
StringBuilder sb = new StringBuilder
sb.append("stuff here").append("more stuff here").append.....
A string is just a string and can't be changed.

- 3,469
- 7
- 41
- 90