Java Interview QuestionsStrings

String vs StringBuffer vs StringBuilder

Posted On
Posted By admin

A very common interview question is to ask the difference between String, StringBuffer and StringBuilder. So in this blog post, I am going to explain how they are different.

 

What is a String?

A String is a Java class. It is designed to hold a set of characters like alphabets, numbers, special characters, etc. String objects are constants, their values cannot be changed after they are created. So, String objects are also called immutable objects. For example, consider the following code snippet:


String str = "abc"; //line 1

str = str+"xyz"; //line 2

When the line 2 is executed, The object “abc” remains as it is and a new object is created  with the value “abc” appended with “xyz”.  The object reference “str” no longer points to the memory address of “abc“, but it points to the address of “abcxyz“. And what about “abc“? It continues to exist as it is until it is garbage collected.Refer this blog post to read more.

What is a StringBuffer?

StringBuffer is a peer class of String that provides much of the functionality of strings. While a String is immutable, a StringBuffer is mutable. For example, consider the following code snippet:


StringBuffer buf = new StringBuffer("abc"); //line 1
buf = buf.append("xyz"); //line 2

In this case, when line 2 of the code is executed, the String “xyz” is appended to the String “abc” in the same object called “buf”. So a new object is not created when line 2 of the code is executed.

What is a StringBuilder?

StringBuilder is also a mutable class that allows you to perform String manipulation. It was introduced in Java 1.5. It is basically an unsynchronised version of StringBuffer. So while the StringBuffer is thread-safe, the StringBuilder is not. Since the StringBuilder is not synchronised,  it is slightly more efficient than StringBuffer.

How are they similar?

All three String classes can be used to perform String manipulation.

What differentiates them?

So as mentioned earlier, here are the key differences between the String, StringBuffer and StringBuilder classes

  • A String is immutable, StringBuffer and StringBuilder are mutable
  • StringBuffer is thread-safe while the StringBuilder is not
  • StringBuilder is slightly more efficient than StringBuffer
If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment