String vs StringBuffer vs StringBuilder in Java

It is one of the most popular interview question.

String

1.String is immutable  (once created can not be changed )object.

Example

String  test= "Hi" ;
// The above object is stored in constant string pool and its value can not be modified.
 
 test="Bye" ;    //new "Bye" string is created in constant pool and referenced by the demo variable            
// "Hi" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string

2.immutable object in Java is thread safe ,that means String is also thread safe. String can not be used by two threads simultaneously.

StringBuffer

1.StringBuffer is mutable(one can change the value of the object)

2.Both  StringBuffer and StringBuilder have same methods but methods in  StringBuffer are synchronized.

3.Since StringBuffer is synchronized it is thread safe .

StringBuilder

1.StringBuffer is is mutable(one can change the value of the object).

2.Both StringBuffer and StringBuilder have same methods but methods in  StringBuilder are not  synchronized.

3.Since StringBuilder is not synchronized it is not thread safe .

Note:Use String if you need immutability, use StringBuffer if you need mutable + thread-safety and use StringBuilder if you need mutable + without thread-safety.

Advertisements
This entry was posted in Interview, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s