Showing posts with label mutable. Show all posts
Showing posts with label mutable. Show all posts

Wednesday, July 23, 2014

What is difference between String,StringBuffer and StringBuilder

The main difference is w.r.t. whether the objects are mutable or immutable.
Immutable means that once the object is created the value inside the object cannot be changed. Mutable object allows the value inside object to be changed whenever needed.
The main difference between String, StringBuffer and StringBuilder is that Sting objects are immutable whereas StringBuffer and StringBuilder objects are mutable.
Suppose we have String object as
String str="Hello";
str = "Good Morning";
str is assigned value “Hello” and further if str is assigned new value “Good Morning” . it will not replace “Hello” with “Good Morning” and it will have both the strings in string literal pool but str will start pointing to “Good Morning”. If we keep on changing value of str like this, string literal pool will have all those previous strings which increases size of string literal pool and every time new string object is created.
So if there are frequent changes in string contents then StringBuffer or StringBuilder should be used.
DIFFERENCE BETWEEN STRINGBUFFER AND STRINGBUILDER
StringBuffer and StringBuilder both have same methods with only difference of synchronization. All the methods of StringBuffer are synchronized while the methods of StringBuilder are not synchronized. The synchronized methods are thread safety implemented for thread environment. So if you are using threads in your program, StringBuffer should be used otherwise StringBuilder can be used.
Here is an example which will clear the exact difference between them.
String a = "Hi";
StringBuffer b = new StringBuffer("Hello");
StringBuilder c = new StringBuilder("Hello");
a=a.append("Java");
b=b.append("Java");
c=c.append("Java");
Here new object is created for String with value “Hi Java”, whereas in case of StringBuffer and StringBuilder, the same object is updated with the value “Hello Java”.

Finally when to use which string class
• String: if string operations are not used in your programs then you should use String class.
• StringBuffer: if you are using threads then you should use StringBuffer class as methods are synchronized
• StringBuilder: if you are not using threads then should use StringBuilder class.