Difference between String, StringBuilder and StringBuffer in Java commonly asked question in interview

String is one of the most commonly used class in java used by a developer. String can be used for multiple purposes for run time values, string manipulations , etc. But many developers ignore the fact that Strings are IMMUTABLE. That is whenever a value for string is modified a new internal memory is allocated for storing the string value and thus the previous value remains unchanged.

Being IMMUTABLE and final in nature it makes its hash code value to be cached and thus used in hash map for faster hash map key reference and also becomes useful in multiple thread execution being a thread safe value.

Accessive use of string operations in your code like upper case, lower case, concatenation, sub string leads to performance issue. So to manipulate the strings without creating STRING GARBAGE can be done with either StringBuffer or with StringBuilder.

Now, next question comes here whether we want the data to be thread safe or not ?

StringBuffer and StringBuilder both are mutuable and thus operation done on the StringBuffer or StringBuilder object does not create any new object. The main difference is that StringBuffer has all its public methods are SYNCHRONIZED which makes it thread safe but also makes it slow in execution. On the Other hand, StringBuilder is not synchronized and has same methods as StringBuffer has.

So we can summarize the following
1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator “+” used in String is internally implemented using either StringBuffer or StringBuilder.

Developer should use String if require immutable objects
Developer should use of StringBuffer if require object to be mutable and thread safe
Developer should use StringBuilder if require mutable and no thread safe.

Bookmark and Share