String vs StringBuffer vs StringBuilder

String vs StringBuffer vs StringBuilder

Java provides different built-in classes around String such as String, StringBuilder, StringBuffer and many more. String object is widely used by programmers, which has certain features which restrict it’s usage, such as Immutable and thread safe. The thread safe is good is in case of multi-threading environment but immutable feature is a bottle neck in a situation where manipulation of string is required as it’ll lead to successive creation of different string object whenever given string object is manupulated. This lead to creation of StringBuffer and StringBuilder in which immutability has been removed. Here in this post we’ll see comparison of String vs Stringbuffer vs Stringbuilder.

Below listed are some common features and differences between String, StringBuffer and StringBuilder.

String is immutable i.e once created can not be changed.StringBuffer is mutable i.e one can change the value of the object.StringBuilder is same as StringBuffer i.e mutable.
The object created as a String is stored in the Constant String PoolThe object created through StringBuffer is stored in the heap.Similar to StringBuffer, the object created through StringBuilder is stored in the heap.
String is immutable and every immutable object is thread safe. So, String is thread safe.Each method in StringBuffer is synchronized i.e StringBuffer is thread safeStringBuilder is not thread safe.
The purpose of String is different than StringBuffer and StringBuilder we will not compare the performance of String with StringBuffer and StringBuilderThe performance of the StringBuffer hits due to thread safe property and it is slower as compare to StringBuilder StringBuilder is not synchronized so it is Faster as compare to StringBuffer.

Sample code to compare the performance of StringBuffer and StringBuilder.


Stay tuned for more updates!

Leave a Reply

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