Question

I know this question has been answered many times in many sites many years ago.:P Still I have some doubt so thought of posting this. The basic difference is, String is immutable and each time we do any operation on String it creates a new String Object.

Ex:-

String str = "some"; str = str + " text"

In above case 2 new Strings get created instead of modifying the existing str which can be avoided by using StringBuffer.

Ex:- StringBuffer str = new StringBuffer(); str.append("try"); str.append("this");

My question here is, to append method we are passing a String again. Do new String objects not get created for "try" and "this" in String pool in above case.

Was it helpful?

Solution

Yes, new String objects get created for "try" and "this". The benefit here is that the StringBuffer stores the string of characters internally as a dynamically resized array.

It's more obviously beneficial if we were to concatenate more than two Strings:

"try" + "this" + "test"

This would potentially create 5 String objects because you need intermediate values. (Technically concatenation of literals is performed at compile time so this is just a conceptual example.) It would also be typical for a compiler to refactor the above snippet in to using StringBuilder anyway if they were not literals.

StringBuilder is a newer and non-synchronized version of StringBuffer. In general, you should prefer StringBuilder. The difference between these two classes is covered in "StringBuilder and StringBuffer in Java".

OTHER TIPS

The main difference (besides "StringBuffer" being mutable and "String" being immutable) is performance. I found a nice explanation here

However I also found that StringBuilder is preferred over StringBuffer because StringBuffer is synchronized and StringBuilder is not.

for just some strings, we can't really see any difference.

so I think an example can show you why you should use StringBuffer (or StringBuilder, according to your needs) instead of string concatenation using +

try this and see for yourself

public class UseSB {
    static int x = 100000;
    public static void main(String[] args) {
        long i1 = System.currentTimeMillis();
        main1();
        long i2 = System.currentTimeMillis();
        main2();
        long i3 = System.currentTimeMillis();
        System.out.println(i2-i1);
        System.out.println(i3-i2);
    }

    public static void main1() {
        String s = "x";
        for(int i=0;i<x;i++){
            s = s + Integer.toString(i);
        }
        System.out.println(s.length());
    }

    public static void main2() {
        StringBuffer s = new StringBuffer("x");
        for(int i=0;i<x;i++){
            s.append(Integer.toString(i));
        }
        System.out.println(s.toString().length());
    }

}
  • String: String is immutable (once created cannot be changed) object. The object created as a String is stored in the Constant String Pool. Every immutable object in Java is thread safe, that implies String is also thread safe. A String can not be used by two threads simultaneously. String once assigned can not be changed.

  • StringBuffer: StringBuffer is mutable. It means one can change the value of the object. The object created through StringBuffer is stored in the heap. StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

    Due to this it does not allow two threads to simultaneously access the same method. Each method can be accessed by one thread at a time.

    But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property. Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class.

  • StringBuilder: StringBuilder is same as the StringBuffer, that is it stores the object in the heap and it can also be modified. The main difference between StringBuffer and StringBuilder is that StringBuilder is also not thread safe. StringBuilder is fast as it's not thread safe.

Source: http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top