StringBuffer and StringBuilder

In Java, both StringBuffer and StringBuilder are classes used to create and manipulate mutable strings (unlike String, which is immutable).

Here’s the comparison:


πŸ”‘ 1. Mutability

  • Both StringBuffer and StringBuilder create mutable string objects (content can be changed without creating new objects).

πŸ”‘ 2. Thread Safety

  • StringBuffer
    • Thread-safe, because its methods are synchronized.
    • Suitable for multi-threaded environments.
    • Slightly slower due to synchronization overhead.
  • StringBuilder
    • Not thread-safe (no synchronization).
    • Suitable for single-threaded environments.
    • Faster than StringBuffer.

πŸ”‘ 3. Performance

  • StringBuffer β†’ Slower (due to synchronization).
  • StringBuilder β†’ Faster (no synchronization).

πŸ”‘ 4. Example

public class Test {
    public static void main(String[] args) {
        // Using StringBuffer
        StringBuffer sb1 = new StringBuffer("Hello");
        sb1.append(" World");
        System.out.println("StringBuffer: " + sb1);

        // Using StringBuilder
        StringBuilder sb2 = new StringBuilder("Hello");
        sb2.append(" World");
        System.out.println("StringBuilder: " + sb2);
    }
}

βœ… Output:

StringBuffer: Hello World
StringBuilder: Hello World

πŸ”‘ 5. When to Use

  • Use StringBuffer if:
    • Multiple threads may access/modify the string simultaneously.
  • Use StringBuilder if:
    • Only a single thread will modify the string (most common case).

Leave a Reply