What is the difference between String class and StringBuffer class?
-
I'm surprised a google search provided no results?Mitch Wheat– Mitch Wheat2013-07-27 01:41:30 +00:00Commented Jul 27, 2013 at 1:41
-
oops. sorry for asking this question.siddhu99– siddhu992013-07-27 01:45:57 +00:00Commented Jul 27, 2013 at 1:45
-
StringBuffer is a legacy class and String is not. Use StringBuilder if you can (as the Javadoc states)Peter Lawrey– Peter Lawrey2013-07-27 08:05:16 +00:00Commented Jul 27, 2013 at 8: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.
"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.