0% found this document useful (0 votes)
2 views

Comparison Between String, StringBuilder, And StringBuffer.

String is immutable and safe for constant text, while StringBuilder is mutable and best for performance in single-threaded environments. StringBuffer is also mutable but thread-safe, making it suitable for multi-threaded applications. All three classes are part of the java.lang package and do not require additional imports.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Comparison Between String, StringBuilder, And StringBuffer.

String is immutable and safe for constant text, while StringBuilder is mutable and best for performance in single-threaded environments. StringBuffer is also mutable but thread-safe, making it suitable for multi-threaded applications. All three classes are part of the java.lang package and do not require additional imports.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like