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!

146 comments

  1. Yes,its good and clear and easily to understood

  2. @Ramesh “finally” always trumps… so even if you have a return in your try, finally would still be called and since there is a return in finally, that would be executed.

    A very bad practice by the way. ‘finally’ should be used for cleanup jobs and other stuff that normally would not obstruct your program logic.

  3. Its a very good explaination…Very easy to understand…Keep on doing it…!

  4. Why isn’t there a reverse method in the String Class,Whereas the reverse method is provided in StrintBuilder Class.When i asked this question to many people, the answer which i got was “String reversal is a complex opeartion hence it was not provided in String”.But my argument is ,toLowerCase,toUpperCase are present in String ,then why not reverse.How can you say only String reversal is a complex opeartion while tolowercase ans toUppercase are not.

  5. So if I add more chars to a stringbuffer object you say that an existing object will be modified, but how long will it be modified?
    There must be some limit/capacity of this existing object, after which a new object will be created on the heap!
    Pls comment!

  6. explanation is good…..but examples are not given about stringbuffer and string bulider…

  7. Is good and clear and very easy to understood… keep it up by posting such tech spec….

  8. explanation good, but i want examples regarding String and StringBuffer

  9. You can check StringBuilder examples here -http://www.techtamasha.com/heres-how-you-use-stringbuilder/30

  10. how can we say that stringbuilder is powerful in compare to stringbuffer. i want a suitable answer with example.

  11. If provided examples it would be better

  12. i want the simple examples on stringbuffer and stringbuilder,explanation on these two are simply clear

  13. It’s good explanation…:)

  14. Its Really Good. Nice and Clear Explanation…

  15. Nice,Clear and EASY Explanation….Thanks

  16. excellent explanation,please can you clarify how string objects are mutable with coding………..Thanks in advance please replay to my mail

    Regards
    Sudhakar

  17. Great! Keep the helpful blog posts coming, I can’t tell you how helpful this post was!

  18. Nice explanation.

  19. very good info. provide in yr site

  20. very Easy Explanation.Thank.

  21. Thanks, it is very helpfull, goodluck.

  22. it’s very good and easily understand by the any person

  23. Great Explanation! it was helpful…

  24. @ harshad: new object will not be ceated until you explicitly use new operator and for existing object if u add more characters or modify it then jvm automatically provides required memory….

  25. Hi
    nice explanation…….
    I have a doubt performance wise string buffer and string builder are better than string then why cant we use string buffer or string builder in every case instead of string

  26. @sudhakar – Hope this will clarify you string immutable doubt.

    public class STDALONE {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    //String creates a new object internally when string is use “+” or concat.

    System.out.println(” String immutable example start here”);
    String str = “one”;

    System.out.println(” str hashcode : “+str.hashCode());
    str=str;
    System.out.println(” str=str hashcode : “+str.hashCode());

    str=str.concat(“two”);
    System.out.println(” str concat with two : “+str.hashCode());
    str=str;
    System.out.println(” str=str hashcode : “+str.hashCode());

    str=str+”three”;
    System.out.println(” str + op with three : “+str.hashCode());
    str=str;
    System.out.println(” str=str hashcode : “+str.hashCode());

    System.out.println(” String immutable example End here”);

    System.out.println(“”);
    //StringBuilder/StringBuffer will not create new operator for every append.

    System.out.println(” StringBuilder/StringBuffer example starts here”);
    StringBuilder builder = new StringBuilder();

    System.out.println(“builder : “+builder.hashCode());
    builder.append(“one”);
    System.out.println(“builder two : “+builder.hashCode());
    builder.append(“two”);
    System.out.println(“builder three : “+builder.hashCode());
    builder.append(“three”);
    System.out.println(“builder four : “+builder.hashCode());

    System.out.println(” StringBuilder/StringBuffer example Ends here”);

    }
    }

  27. Good Explanation..

  28. Vipul Chaudhari

    Good Explanation. Needs more examples on the same.

    Keep it up…..!!!!

  29. difference between String Builder and String Buffer

    is synchronized and a synchronized is not clearly under stand please, doubt clear with some more example.

  30. Excellent definition. The way you explained was very easy to understand… I appreciate… keep it up…

  31. Nice Post. I’ve also jot down points of difference between String, StringBuffer and StringBuilder. Click below to read
    Difference between String, StringBuffer and StringBuilder in Java

  32. StringBuffer is thread safe and sychronized but still why StringBuilder is created in Java 1.5

  33. Great!.Easy to understanding

    Thanks

  34. awesome Tutorial .!!

  35. nice explanation that is most helpful to new student.

  36. Its a nice description i never seen the difference between string buffer and string builder .

    I really appreciate about this topic ..
    please keep on posting :P

  37. Thank you! It’s very easy to understand.

  38. thank u very moch :)

  39. thanks a lot for the Explanation. It clarifies the differnces between the String Object, stringBuffer and stringBuilder.

  40. great explanation….chanceless

  41. Thanks,i learn lot of things….

  42. Good Explanation

  43. Nicely explained!!!

  44. Awesome!. It is one of the simplest way of explanation.Great !. Thank you once again.

  45. nice info..

Leave a comment