Difference between String, StringBuffer and StringBuilder

In Java, String, StringBuffer and StringBuilder classes are widely used. In many scenarios, any of them can be used. However, there are minor differences between these classes.

String

String is immutable and defined as a final class. As all immutable objects are thread safe, String is thread safe too.

Part of String class source code in Java

When a String object is created, it will be saved in the String Constant Pool. Let’s look at the code:

string_ref_1

One more example:

Output:

The diagram shows what happened:
string_ref_2

step 1: when “ABC” is created, variable str1 is its reference;
step 2: when “EFG” is created, variable str2 is its reference;
step 3: when str1 refers to String “EFG”, “ABC” has no reference

Let’s see one more example:

output

The diagram shows what happened:
string_ref_3

  • String literals with same values will refer to the same String object
  • String objects created using new operator will be different from literals

StringBuilder

StringBuilder is a mutable sequence of characters. The object created through StringBuilder is stored in the heap. StringBuilder provides an API compatible with StringBuffer, but with no guarantee of synchronization. The class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations [Java Doc].

StringBuffer

StringBuffer is mutable. The object created through StringBuffer is stored in the heap. StringBuffer has the same interface as StringBuilder. However, the methods in StringBuffer are synchronized, and StringBuffer object is thread safe. As each method is synchronized in StringBuffer, the performance of StringBuffer will be hit a little bit compared to StringBuilder.

Conclusion

The difference between String, StringBuffer and StringBuilder includes:

  • String is immutable while StringBuffer and StringBuilder is mutable object
  • StringBuffer is synchronized and thread safe while StringBuilder is not.
  • If the text will be accessed by single thread, use StringBuilder to replace StringBuffer to get better performance
  • If the text is not going to change, use String (over StringBuilder / StingBuffer).
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">