Interview #113: Java: Difference between StringBuffer and StringBuilder?

Interview #113: Java: Difference between StringBuffer and StringBuilder?

In Java, both StringBuffer and StringBuilder are mutable alternatives to the String class. While String objects are immutable, meaning they cannot be changed after creation, StringBuffer and StringBuilder allow modifications without creating new objects.

Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245

However, there are key differences between StringBuffer and StringBuilder, primarily in terms of thread-safety and performance.

1. Introduction to StringBuffer and StringBuilder

StringBuffer (Thread-Safe, Synchronized)

  • Introduced in Java 1.0
  • Synchronized, meaning it is thread-safe and can be used in multi-threaded environments.
  • Because of synchronization, it is slower than StringBuilder.

StringBuilder (Not Thread-Safe, Faster)

  • Introduced in Java 5
  • Not synchronized, meaning it is not thread-safe but is faster in single-threaded environments.
  • Recommended for cases where synchronization is not required.


2. Key Differences Between StringBuffer and StringBuilder

3. Code Examples and Performance Comparison

Example 1: Using StringBuffer (Thread-Safe)

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.append(" World");
        System.out.println(sb); // Output: Hello World
    }
}        

  • Since StringBuffer is synchronized, it ensures thread safety in concurrent applications.
  • Suitable for multi-threaded programs where multiple threads modify the same string.


Example 2: Using StringBuilder (Faster, Not Thread-Safe)

public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");
        System.out.println(sb); // Output: Hello World
    }
}        

  • Since StringBuilder is not synchronized, it is much faster than StringBuffer.
  • Suitable for single-threaded applications where thread safety is not a concern.


Example 3: Multi-threaded Scenario

Let's see how StringBuffer is thread-safe while StringBuilder is not.

Using StringBuffer in Multi-threading

class StringBufferThread extends Thread {
    static StringBuffer sb = new StringBuffer("Hello");

    public void run() {
        sb.append(" World");
        System.out.println(sb);
    }

    public static void main(String[] args) {
        StringBufferThread t1 = new StringBufferThread();
        StringBufferThread t2 = new StringBufferThread();

        t1.start();
        t2.start();
    }
}        

Output (Thread-safe behavior):

Hello World
Hello World        

  • Both threads safely update StringBuffer because it is synchronized.


Using StringBuilder in Multi-threading (Not Safe)

class StringBuilderThread extends Thread {
    static StringBuilder sb = new StringBuilder("Hello");

    public void run() {
        sb.append(" World");
        System.out.println(sb);
    }

    public static void main(String[] args) {
        StringBuilderThread t1 = new StringBuilderThread();
        StringBuilderThread t2 = new StringBuilderThread();

        t1.start();
        t2.start();
    }
}        

Output (Inconsistent, due to lack of synchronization):

Hello World
Hello World World        

  • Since StringBuilder is not synchronized, simultaneous modifications by multiple threads cause unpredictable results.


4. Performance Comparison: Which One is Faster?

Since StringBuilder is not synchronized, it is faster than StringBuffer in single-threaded applications.

Benchmark Test

public class StringPerformanceTest {
    public static void main(String[] args) {
        long startTime, endTime;

        // Testing StringBuffer Performance
        StringBuffer sb = new StringBuffer("Test");
        startTime = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            sb.append("A");
        }
        endTime = System.nanoTime();
        System.out.println("StringBuffer Time: " + (endTime - startTime) + " ns");

        // Testing StringBuilder Performance
        StringBuilder sb2 = new StringBuilder("Test");
        startTime = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            sb2.append("A");
        }
        endTime = System.nanoTime();
        System.out.println("StringBuilder Time: " + (endTime - startTime) + " ns");
    }
}        

Expected Result:

  • StringBuilder performs faster than StringBuffer because of the absence of synchronization overhead.


5. When to Use StringBuffer vs. StringBuilder?

? Use StringBuffer when:

  • Your program is multi-threaded and requires synchronization.
  • Multiple threads modify the same string concurrently.

? Use StringBuilder when:

  • Your program is single-threaded or does not require synchronization.
  • You need faster performance for string modifications.


6. Conclusion

  • StringBuffer is thread-safe but slower due to synchronization.
  • StringBuilder is faster but not thread-safe, making it better for single-threaded applications.
  • Choosing between the two depends on whether thread safety is required.


Harshil Patel

Sr. Software Automation Engineer || SDET || Selenium || Java || C# || Cucumber BDD || Agile || TestNG || NUnit || Maven|| POM || WebdriverIO || Rest API Testing || Appium || JMeter || Git || JIRA || CSPO || CSM || Docker

4 天前

Well put

回复

要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章

社区洞察