Java FAQ: Top Questions
19. What is the difference between String, StringBuilder, and StringBuffer?
String
,
StringBuilder
, and
StringBuffer
handle text, but differ in mutability and thread safety.
-
String:
- Immutable; any modification creates a new object.
- Thread-safe due to immutability.
- Suitable for fixed text (e.g., constants).
-
StringBuilder:
- Mutable; modifies the same object.
- Not thread-safe; faster for single-threaded operations.
- Ideal for string manipulation in loops.
-
StringBuffer:
-
Mutable; like
StringBuilder
but thread-safe (synchronized methods). - Slower due to synchronization overhead.
- Used in multithreaded environments.
-
Mutable; like