What is the difference between String, StringBuffer and StringBuilder?

Lets see what are the difference between  String, StringBuffer and StringBuilder

1. String Object is immutable and StringBuffer and StringBuilder are mutable.

String is immutable: if we modify the String object it results creating new object. Creating a new instance every time is expensive.
                                                                                               



Let look at following code :

String output = “I am going to be new”

Int count = 10;

for(int i =0; i<count; i++) {

output += i;   // Creating new object every time.

}

return output;


Above code would build 9 new String objects. Creating new objects is not efficient.

StringBuffer / StringBuilder

StringBuffer / StringBuilder are mutable , doesnt create new objects every time.

So it is useful to use StringBuffer or StringBuilder when we need to modify the contents.
StringBuffer output = new StringBuffer(200);

Output.append(“I am not going to change every time”);

for(int i =0; i<count; i++) {

output.append(i);

}


return output.toString();  // Only second object created here.


In above code only two object got created.

Along with  'overloaded mathematical operators’ (“+”) , some other methods like concat(), trim(), substring(), and replace() in String classes  generate new string instances. So for computation intensive operations, it useful to have So use StringBuffer or StringBuilder instead of String.



2. Strings are cannonical

Strings can be created using cannonical form :

cannonical representation of the strings

String s="I am a String";//cannonical form

In case of stringbuffer we need to instantiate for every time we are using it.

e.g.

StringBuffer sb=new StringBuffer("I am a StringBuffer");//normal form

3. StringBuffer is synchronous and StringBuilder is asynchronous:

StringBuilder is not thread safe, so if you have the text which is accessed from a single thread then you can go with StringBuilder because StringBuilder is unsynchronized.

StringBuffer is thread safe, so if you text is getting accessed from multiple threads StringBuffer is the perfecct choice.

Due to synchronous nature of StringBuffer , StringBuffer is slower than String and StringBuilder.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment