String vs StringBuffer vs StringBuilder

Difference between String, StringBuffer and StringBuilder are popular interview questions in java.

Question 1 : What is difference between string and stringbuffer or stringbuilder.
Answer : String is an immutable class in java so you can not change it’s object once it is created. If you want to perform operation on this object then it will create new object. But when you want to perform operations on string value without creating multiple objects then java has provided two classes for this functionality. These classes are StringBuffer and StringBuilder. Both of these classes have all functionality provided by string without being immutable. So when should we use these two classes depends on our requirement.

For eg: If we require string value after performing multiple operations basis on some conditions then we should go for these classes.

Question 2 : What is the difference between StringBuffer and StringBuilder.
Answer : Next question of interviewer will be, If java have provided two classes then what is the difference between them or why there is two classes. Difference between these two classes is. StringBuffer is thread-safe so basically this class have synchronised methods so only one thread will access these method at a time and can change string value, so next thread will get updated value. When you are going to perform operation on string value in multi-threading environment then we should always use StringBuffer. On the other hand StringBuilder have same functionality as StringBuffer but it is not thread-safe. Then why should we use stringbuilder. Well when we want to perform operation on stringvalue in single threaded environment then we should use StringBuilder because it is much faster then stringbuffer. When we need performance in single thread environment then StringBuilder is right choice.

Other related posts are :
Top 10 spring interview questions and their answers. Spring basic concepts.
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Set datasource spring bean properties dynamically if server is not available

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.


2 thoughts on “String vs StringBuffer vs StringBuilder

  1. Pingback: String interview questions and answers | Techno Tailor

  2. Pingback: Top 10 spring interview questions and their answers. Spring basic concepts. | Techno Tailor

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s