Difference between String and StringBuffer/StringBuilder

       The difference between String and StringBuffer/StringBuilder is that String object is immutable(the value cannot be changed), where as StringBuffer/StringBuilder objects are mutable(value can be changed). Then the next question that comes to our mind is “If String is immutable then how can we able to change the contents of the object?” . Well, when we change the value of the string, 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 str = “Hello”;
Next, you want to append “World” to the same String. What do you do?
  •   str = str + ” World”;
          When you print the contents of str the output will be “Hello World”. Although we made use of the same object(str), 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. This leads to performance issues. To over come these performance issues we use StringBuffer/StringBuilder. When we use StringBuffer/StringBuilder, as these two are immutable we can change their values easily. 
        The difference between StringBuffer/StringBuilder is that, 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).

1 comment:

  1. String is an immutable class while StringBuilder & StringBuffer are mutable classes. StringBuffer is synchronized while StringBuilder is not.

    Below link can be useful to find more differences between String, StringBuffer & StringBuilder

    Difference between String, StringBuffer and StringBuilder

    http://newtechnobuzzz.blogspot.com/2014/07/difference-between-string-stringbuffer.html

    ReplyDelete