Search code examples
javastringstringbuffer

Difference between String class and StringBuffer class


What is the difference between String class and StringBuffer class?


Solution

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