String vs StringBuilder

In Java, String and StringBuilder both represent sequences of characters, but they have key differences in terms of mutability, performance, and usage.

1. Mutability:

1. String is immutable, meaning once a String object is created, it cannot be modified. Any operation that changes a String (like concatenation, replacement, etc.) creates a new String object.

2. StringBuilder is mutable, meaning you can modify the content of a StringBuilder object without creating new objects. This makes it more efficient when performing repeated modifications.

Example


public class StringVsStringBuilder {
    public static void main(String[] args) {
        // String (immutable)
        String str = "Hello";
        str = str + " World";  // A new String object is created
        
        // StringBuilder (mutable)
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");  // The same StringBuilder object is modified
        
        System.out.println(str);  // Output: Hello World
        System.out.println(sb.toString());  // Output: Hello World
    }
}

2. Performance:

1. String can be inefficient for repeated concatenations because every modification creates a new String object, which results in extra memory usage and processing time.

2. StringBuilder is designed for scenarios where you need to perform many modifications (like appending, inserting, or deleting characters), and it performs these operations more efficiently by modifying the internal character array without creating new objects.

Example:


public class PerformanceExample {
    public static void main(String[] args) {
        // Using String (inefficient for multiple concatenations)
        String str = "";
        long startTime = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            str += "a";  // Each concatenation creates a new String object
        }
        long endTime = System.nanoTime();
        System.out.println("Time with String: " + (endTime - startTime) + " ns");

        // Using StringBuilder (efficient for multiple concatenations)
        StringBuilder sb = new StringBuilder();
        startTime = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            sb.append("a");  // Modifies the same StringBuilder object
        }
        endTime = System.nanoTime();
        System.out.println("Time with StringBuilder: " + (endTime - startTime) + " ns");
    }
}

3. Thread Safety:

1. String is inherently thread-safe since it is immutable, meaning multiple threads can safely access the same String without synchronization.

2. StringBuilder is not thread-safe. If you need thread safety, you can use StringBuffer (which is thread-safe but slower than StringBuilder).