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.
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 “abc_xyz_”. And what about “abc”? It continues to exist as it is until it is garbage collected.Refer this blog post to read more.
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.
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.
All three String classes can be used to perform String manipulation.
So as mentioned earlier, here are the key differences between the String, StringBuffer and StringBuilder classes