Skip to content

Difference between String and String Buffer class

The String and StringBuffer classes in Java both handle sequences of characters but have significant differences in their functionality, mutability, and performance characteristics. Understanding these differences helps in choosing the right class for a given use case.


Key Differences Between String and StringBuffer

AspectStringStringBuffer
MutabilityImmutable: Any modification creates a new object.Mutable: Modifications are made in the same object.
PerformanceSlower for repeated modifications due to object creation overhead.Faster for repeated modifications due to in-place changes.
Thread-SafetyNot thread-safe.Thread-safe (synchronized methods).
Usage ScenarioBest for fixed or infrequently modified text.Best for frequently modified text, especially in multi-threaded environments.
Methods for ModificationProvides methods like concat(), but these return new strings.Provides methods like append(), insert(), replace(), etc., that modify the object directly.
Memory UsageMay lead to higher memory usage due to multiple objects.More memory-efficient for frequent modifications.
SpeedSlower for multiple changes due to immutability.Faster for multiple changes due to mutability.

Detailed Comparison

1. Immutability vs. Mutability

  • String:
    • Strings in Java are immutable. Once created, the value of a String object cannot be changed.
    • Any operation that modifies a string (like concatenation) creates a new String object.
    • Example:

String str = “Hello”;

str = str + ” World”;

System.out.println(str); // “Hello World”

Here, str + ” World” creates a new String object. The old “Hello” object remains in memory until garbage collected.

  • StringBuffer:
    • StringBuffer is mutable, meaning changes can be made to the same object without creating a new one.
    • Example:

StringBuffer sb = new StringBuffer(“Hello”);

sb.append(” World”);

System.out.println(sb); // “Hello World”

Here, the content is directly modified in the existing StringBuffer object.


2. Performance

  • String:
    • Slower for repeated modifications due to the creation of multiple objects.
    • Example:

String str = “”;

for (int i = 0; i < 5; i++) {

    str += i; // Creates a new String object in every iteration.

}

System.out.println(str); // “01234”

  • StringBuffer:
    • Faster for repeated modifications since changes are made in-place.
    • Example:

StringBuffer sb = new StringBuffer();

for (int i = 0; i < 5; i++) {

    sb.append(i); // Modifies the same StringBuffer object.

}

System.out.println(sb.toString()); // “01234”


3. Thread-Safety

  • String:
    • Strings are immutable, so they are inherently thread-safe. Multiple threads can safely use a String object without synchronization.
  • StringBuffer:
    • StringBuffer is thread-safe because its methods are synchronized.
    • Example:

StringBuffer sb = new StringBuffer(“Hello”);

sb.append(” World”); // Synchronized modification.


4. Commonly Used Methods

MethodStringStringBuffer
Concatenationconcat(String str)append(String str)
InsertionNot supported directly.insert(int offset, String str)
DeletionNot supported directly.delete(int start, int end)
ReplacementNot supported directly.replace(int start, int end, String str)
ReverseNot supported directly.reverse()

Examples

String Example

public class StringExample {

    public static void main(String[] args) {

        String str = “Hello”;

        str = str + ” World”; // Creates a new String object

        System.out.println(str); // Output: Hello World

    }

}

StringBuffer Example

public class StringBufferExample {

    public static void main(String[] args) {

        StringBuffer sb = new StringBuffer(“Hello”);

        sb.append(” World”); // Modifies the same object

        System.out.println(sb); // Output: Hello World

    }

}


When to Use Which?

ScenarioPreferred ClassReason
Text is fixed or rarely modified.StringImmutability ensures simplicity and safety.
Frequent text modifications.StringBufferFaster and memory-efficient.
Multi-threaded text modifications.StringBufferThread-safe due to synchronized methods.
Single-threaded modifications.StringBuilderSimilar to StringBuffer but faster as it’s not synchronized.

Comparison with StringBuilder

StringBuilder is similar to StringBuffer but is not synchronized, making it faster in single-threaded environments.

AspectStringBufferStringBuilder
Thread-SafetyThread-safeNot thread-safe
PerformanceSlightly slowerFaster
Usage ScenarioMulti-threadedSingle-threaded

Conclusion

  • Use String for immutable text or infrequent modifications.
  • Use StringBuffer for mutable text in multi-threaded environments.
  • For single-threaded environments requiring frequent modifications, consider using StringBuilder instead of StringBuffer for better performance.