0

What is the difference between String class and StringBuffer class?

3
  • I'm surprised a google search provided no results? Commented Jul 27, 2013 at 1:41
  • oops. sorry for asking this question. Commented Jul 27, 2013 at 1:45
  • StringBuffer is a legacy class and String is not. Use StringBuilder if you can (as the Javadoc states) Commented Jul 27, 2013 at 8:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You may want to mention differences in thread-safety as well.
Or simply not waste your time. This is clearly a duplicate question ... multiple times over.
0

"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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.