Difference String StringBuffer and StringBuilder

We will see the differences between String, StringBuffer and StringBuilder.
The main differences are related to thread safe nature and performance.

Difference String StringBuffer and StringBuilder

String

1. String is immutable – So string is Thread Safe.
2. Any operations on String, like concat can take more time in comparison with StringBuffer and StringBuilder.
3. If you are going to use static text/constants or if your data is not going to change between 2 threads – then use String.

StringBuffer

1. StringBuffer is mutable but all methods of StringBuffer are synchronized, So StringBuffer is Thread Safe.
2. But ThreadSafe impacts the performance, StringBuffer is less efficient in terms of performance.
3. If you are going to change the data which will be used by multiple threads then only use StringBuffer.

StringBuilder

1. StringBuilder is mutable and not synchronized, So StringBuilder is not Thread Safe.
2. But StringBuilder is more efficient than StringBuffer or String when it comes to performing any operations or data manipulations.
3. If you are going to change the data which will be used by only one thread at a time then only use StringBuilder.
For single threaded applications use StringBuilder instead of StringBuffer or Strings for data related operations.

Lets see a example that will show the difference in performance for String StringBuffer and StringBuilder

Output