String vs StringBuffer vs StringBuilder

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 1str = 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 1buf = 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

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set