Give a scenario where StringBuffer is better than the String?

StringBuffer is a better choice when a string needs to be modified frequently in a multithreaded environment. Since its methods are synchronized, it provides thread-safe operations and prevents data inconsistency when multiple threads access the same object.

Key Points: • String is immutable, so every modification creates a new object. • StringBuffer is mutable and updates the same object, improving performance during frequent modifications. • StringBuffer is synchronized, making it safe for concurrent access by multiple threads. • It reduces memory overhead caused by creating numerous String objects. • It is ideal for applications where thread safety and frequent string updates are required.

Example: Consider a multithreaded logging system where multiple threads append log messages to a shared string. Using String would create many temporary objects, while StringBuffer safely updates the same object and prevents data corruption.

Code Example:

public class Demo {

    public static void main(String[] args) {

        StringBuffer log = new StringBuffer();

        log.append("Application Started");
        log.append(" - User Logged In");
        log.append(" - Transaction Completed");

        System.out.println(log);
    }
}

Interview Tip: A concise interview answer is:

"StringBuffer is preferred over String when a string is modified frequently and shared across multiple threads. Since StringBuffer is mutable and thread-safe, it avoids creating unnecessary objects and ensures safe concurrent access."