Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Difference between String, StringBuffer and StringBuilder class in Java.


The main difference between String and StringBuffer class is that the objects of String class are immutable ( that cannot be changed ) while the objects of StringBuffer and StringBuilder class are mutable (that can be changed )
Now here is a question that if String objects are immutable how we are able to change the value of object when we want? Actually when we change the value of a String object, internally a new object is created and our reference variable starts pointing that new object and the previous object still remains in memory as garbage. Thus this create performance issue, and we use StringBuffer and StringBuilder class to create mutable objects.

For Example :

//consider a string object
String A = "Hello" ;
//If we want to append "friend" to this string, we do
A = A + "Friend" ;

When we print the content of A we get "Hello Friend" as the output. But it is the new object of string class that is created. And if we append any further in this string it will create that many objects of String class internally.

However when using StringBuffer/StringBuilder class we can make changes to the value stored as its objects are mutable. Hence append operation would be more efficient if use StringBuffer in place of String class.

To append using StringBuilder class we use append( ) operation as:

StringBuilder A = "Hello" ;
A.append("Friend") ;

And the changes will be made in the Object A

Now, Difference between StringBuffer and StringBuilder

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.


*Also all these three classes are final and hence cannot be extended.

To know more about final keyword click here




This post first appeared on Prepare For Interview And Recruitment Exams While, please read the originial post: here

Share the post

Difference between String, StringBuffer and StringBuilder class in Java.

×

Subscribe to Prepare For Interview And Recruitment Exams While

Get updates delivered right to your inbox!

Thank you for your subscription

×