Comparison: String vs StringBuilder vs StringBuffer
------------------------------------------------------------
1. Mutability
String - Immutable (cannot be changed after creation)
StringBuilder - Mutable (can be modified without creating a new object)
StringBuffer - Mutable (same as StringBuilder)
------------------------------------------------------------
2. Thread Safety
String - Safe (due to immutability)
StringBuilder - Not thread-safe (not synchronized)
StringBuffer - Thread-safe (methods are synchronized)
------------------------------------------------------------
3. Performance
String - Slow for modifications (creates new objects)
StringBuilder - Fast (best choice for single-threaded apps)
StringBuffer - Slower than StringBuilder due to synchronization
------------------------------------------------------------
4. Use Case
String - For constant, unchanging text
StringBuilder - For fast string manipulations in single-threaded environment
StringBuffer - For safe string manipulations in multi-threaded environment
------------------------------------------------------------
5. Example
// String
String s = "Hello";
s = s + " World"; // Creates a new String object
// StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies same object
// StringBuffer
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World"); // Also modifies same object (thread-safe)
------------------------------------------------------------
6. Package
All three are part of java.lang package
No need for additional import
------------------------------------------------------------
Summary
Use String - If string does not change
Use StringBuilder - If performance matters and thread safety is not a concern
Use StringBuffer - If thread safety is required