Difference between String, StringBuffer, and StringBuilder
Here the String is immutable means that you cannot change the object itself, but you can change the reference to the object, whereas StringBuffer and StringBuilder are mutable so they can change their values.
The above code segment creates 500 new string variables. The "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder . In these type of situations you should use the Java StringBuffer/StringBuilder class.
Since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
It is better you use the String object when an immutable structure is appropriate, obtaining a new character sequence from a String may carry an unacceptable performance penalty , either in CPU time or memory.
StringBuffer is synchronized i.e. StringBuffer thread safe. It means two threads can't call the methods of StringBuffer simultaneously. While StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. So, if you aren’t going to use threading then use the StringBuilder class as it'll be more efficient than StringBuffer due to the absence of synchronization. Methods of StingBuilder are not synchronized but in comparison to other Strings, the Stringbuilder runs fastest.
Why we have two classes for same purpose?
StringBuffer is Thread safe and StringBuilder is not. StringBuilder is a new class on StringBuffer Api and it was introduced in JDK 5 and is always recommended if you are working in a Single threaded environment as it is much Faster .