How would you differentiate between a String, StringBuffer, and a StringBuilder?
How would you differentiate between a String, StringBuffer, and a StringBuilder?
726
19-Nov-2021
Updated on 18-Apr-2023
Aryan Kumar
18-Apr-2023In Java, a String, StringBuffer, and StringBuilder are all classes used to store and manipulate text data, but they differ in their functionality, immutability, and thread-safety.
String: A String is an immutable sequence of characters that cannot be changed once created. If you need to modify a String, a new String object must be created. Strings are thread-safe and can be shared among multiple threads.
StringBuffer: A StringBuffer is a mutable sequence of characters that can be modified after creation. StringBuffer is thread-safe, which means multiple threads can access it concurrently without any issue. StringBuffer is useful when there is a need for a mutable sequence of characters that can be modified efficiently without creating a new object every time.
StringBuilder: A StringBuilder is also a mutable sequence of characters, just like StringBuffer. However, StringBuilder is not thread-safe, which means it should not be used in a multi-threaded environment. StringBuilder is faster than StringBuffer, but if thread-safety is a concern, StringBuffer should be preferred over StringBuilder.
In general, String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
Krishnapriya Rajeev
24-Mar-2023String, StringBuffer, and StringBuilder can be differentiated as follows:
SYNTAX:
Ravi Vishwakarma
20-Nov-2021