Please tell me a real time situation to compare
String is immutable, if you try to alter their values, another object gets created, whereas
StringBuilder are mutable so they can change their values.
The difference between
StringBuilder is that
StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use
StringBuilder is more efficient than
- If your string is not going to change use a String class because a
Stringobject is immutable.
- If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a
StringBuilderis good enough.
- If your string can change, and will be accessed from multiple threads, use a
StringBufferis synchronous so you have thread-safety.