String:
The String class represents an immutable sequence of characters.
Once a String object is created, its value cannot be changed.
Whenever operations are performed on a String,
such as concatenation or substring, a new String object is created.
String objects are thread-safe and can be safely shared across multiple threads.
Example: String str = new String("a");
StringBuilder:
The StringBuilder class represents a mutable sequence of characters.
It is designed for situations where the value of the sequence needs to be
modified frequently.
StringBuilder provides methods to append, insert, delete, or
modify the characters in the sequence.
StringBuilder objects are not thread-safe by default, meaning they
should not be shared among multiple threads without
proper synchronization.
Example: StringBuilder sb = new StringBuilder("B");
StringBuffer:
The StringBuffer class is similar to StringBuilder and
also represents a mutable sequence of characters.
However, unlike StringBuilder, StringBuffer is designed
to be thread-safe. It provides synchronized methods,
which means that multiple threads can safely modify a StringBuffer object
without causing any data inconsistency.
However, due to the synchronization overhead,
StringBuffer operations are slower than StringBuilder.
Example: StringBuffer sb = new StringBuffer("c");
To summarize, String is immutable, StringBuilder is mutable but
not thread-safe, and StringBuffer is mutable and thread-safe.
If you need a mutable sequence of characters and do not require thread safety,
StringBuilder is a suitable choice.
If thread safety is required, or if you are working with concurrent environments,
StringBuffer can be used.