Difference between String and StringBuffer/StringBuilder in Java

Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

So suppose you declare a String object:

String myString = “Hello”;

Next, you want to append “Guest” to the same String. What do you do?

myString = myString + ” Guest”;

When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.

Now isn’t that a performance issue?

Yes, it definitely is.

Then how do you make your string operations efficient?

By using StringBuffer or StringBuilder.

How would that help?

Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.

Finally, whats the 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.

Incase you do not know – Here’s how you use StringBuilder

A simple Example to demonstrate that String object is Immutable

Incase you still have any doubts regarding String or StringBuilder then do leave a comment. I’ll be more than eager to help you out.

Note: StringBuilder was introduced in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use StringBuffer)

Link: Have doubts about the ‘final’ keyword? check out my post – Click Here!

206 comments

  1. super answer… Thanks alot..

  2. Nice Explained Answer.

  3. arpit singhal

    thanks a lot

  4. super

  5. navnath gadakh

    g8 ans

  6. Well explained.

    Thanks.

  7. good explanation dude.

  8. very nice real time explanation

  9. Jinesh Gopinathan

    very nice and simple explanation. Thanks

  10. i understood.. but some confused between them. i dont understand when the comparision between mutable and immutable. pls give me some clarify in that

  11. its good explanation

  12. what is thread in that

  13. excellent..but what is the use of string builder…

  14. hey Nice one yar

  15. its useful but we need much more about mutable & imutable object examples

  16. nice explanation

  17. Thanks buddy…

  18. Well explained.

    Thanks a lot.

  19. thank you very much , u explained in great way.

  20. Excellant :)

  21. Good one..

  22. gained some new concepts about stringbuilder and stringbuffer. .very nice. .

  23. can you explain more than this please………..

  24. Thank you for your detailed explanation. Can I assume that multi treading application means running many instance of an application at the same time without breaking the integrity of the data of each running instance of the application? On such application which should be used; StringBuffer or StringBuilder? How my choice of implementation(StringBuffer or StringBuilder) will effect the data and the performance?

  25. thanks a lot

  26. Jaymin Thakkar

    Really Nice Answer !

  27. Nice……….

  28. Super…”high five”..

  29. nice answer man
    can u tell more on this

  30. very clear…..thanks for your answer.

  31. good

  32. Superub explanation of diff btw string and StringBuffer I would like :- see

    String s1=”abc”;
    s1=s1+”def”; —-> here the concept of operator overloading where s1 is caller object “def” is another object to pass as a parameter.

    so internal it look like +Operator(String s2)
    {
    String temp=s1+s2;
    return temp;
    }

    then result become “abcdef”

  33. simply gud…….

  34. Could you please explain me ? what happens when I declare like this :
    String str1 = “abc”+”sdc”+”asdf”+”HI”;
    I meant to ask as to how may Objects would be Created?
    As per my Knowledge, there are 7 objects created..
    Am i true? if I am false Please explain in detail, how many Objects are Created?

  35. @TJ I just searched up a little and realized there’s something called as compile time resolution of Strings.

    So in the example that you specify, supposedly when you compile it would be :

    String str1 = “abcsdcasdfHI”;

    which means there would be only one object. But please do search up a little on this because I too am not sure.

  36. Wow..! Such a Quick Reply.. Appreciated!!
    Yes Mr.Shetty, I would definitely go and investigate on the same. but if u find some thing, Kindly post it.
    Thanks,
    TJ.

  37. Yes, MR Shetty,
    What ever u said is True, it creates a single object at compile time.

    when we say
    String str1 = “abc”;
    string str1 = “abc”+”asdf”;

    then in this case there are 2 objects created..

    but when we say
    String str1 = “abc”+”sdc”+”asdf”+”HI”;
    then only one object is created.

    I Appreciate your answer.
    Thanks.

  38. Simply superb explanation…

    Thanks for the post..

  39. Very well explained….

  40. gud work……………..

  41. Really nice answer… this is what i was looking for…. esp the part that modifications to the value stored in a string object results in creation of new objects….

    Can you tell me wht happens to the older object?

  42. Very nicely explained

  43. Good Explanation dude..thanks a lot

  44. from difference between StringBuffer and StringBuilder in javaStringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class.

  45. i am happy about the answer

  46. Nice Explained Answe

  47. Good one

  48. String means is class,whose contents are not modified..thats ok

    but

    String a=”abc”;
    a=”vvv”// here string contents are modified.but definition is immutable.can explian it.
    System.out.println(a);
    //here output is vvv.

  49. public class Tav2 {

    public static void main(String ar[])
    {
    int a=test();
    System.out.println(a);
    }
    static int test()
    {
    try
    {
    return 1;//why it is not executing
    }catch(Exception e){
    return 2;

    }
    finally{
    return 3;

    }
    }
    }

    Q;what is output and why?I thought try block executing,if it does,output is 1;but it is not

Leave a comment