WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Core Java Β· Intermediate Β· question 24 of 100

What is the difference between a StringBuilder and a StringBuffer in Java?

πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

In Java, both StringBuilder and StringBuffer are classes that represent a mutable sequence of characters. This means that we can modify the sequence of characters in the object after it has been created. However, there is a difference between the two classes in terms of their performance characteristics and thread safety.

StringBuilder is a non-synchronized class, which means that it is not thread-safe. This class is preferred when performance is a priority, as it is faster than StringBuffer. Because StringBuilder is not thread-safe, it is not recommended to use it in multi-threaded applications.

StringBuffer, on the other hand, is a synchronized class, which means that it is thread-safe. This class is used when thread safety is required, such as in multi-threaded applications. However, because StringBuffer is synchronized, it is slower than StringBuilder.

Here’s an example to illustrate the difference between the two classes:

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

In this example, we create a StringBuilder object and a StringBuffer object, and append a string to each object using the append() method. Both classes have the same API, so the code is identical for both objects. We then print the contents of each object using the toString() method.

In summary, StringBuilder and StringBuffer are both classes that represent a mutable sequence of characters in Java. The main difference between the two classes is that StringBuilder is not thread-safe, but faster, while StringBuffer is thread-safe, but slower.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview β€” then scores it.
πŸ“ž Practice Core Java β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Core Java questions & answers β€” PDF + EPUB for $5

All 100 Core Java questions Β· All topics