java

Difference between StringBuffer and StringBuilder in Java

The difference is that StringBuffer is synchronized and therefore thread-safe and StringBuilder is not, but it is a little more efficient and faster.
 

What are StringBuffer and StringBuilder used for?

Since the String class is immutable, a new object is created with every modification. StringBuffer and StringBuilder are basically used like strings as a sequence of characters (chars), with the difference that the objects can be modified.

Suppose we want to extend a string in a loop. In the example below, the string 123456789 is created for the sake of simplicity (better example here). The normal approach would be an empty string as a base, which is expanded in the loop:

public class Main
{
     public static void main(String []args)
     {
        String s = "";
        
        for (int i = 1; i < 10; i++) {
            s += i;
        }
        
        System.out.println(s);
     }
}

Output:

123456789
 
The problem with this version is that the program creates (instantiates) 9 string objects that are not needed: “”, “1”, “12”, “123”, “1234”, “12345”, “123456”, “1234567”, “12345678”. With the StringBuilder only one object is created, which is extended in the loop:

public class Main
{
     public static void main(String []args)
     {
        StringBuilder sb = new StringBuilder();
        
        for (int i = 1; i < 10; i++) {
            sb.append(i);
        }
        
        System.out.println(sb);
     }
}

Output:

123456789

In this version, only two objects are created: a StringBuilder and a String (when calling StringBuilder.toString() in System.out.println())

By the way, internally a char[] array is used which contains the characters. The initial size of this array can be determined with the StringBuilder(int capacity) constructor.
 

java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More
The difference – when is StringBuffer and when is StringBuilder?

StringBuffer must be used if multiple threads can access the object at the same time. If it is guaranteed that only one thread accesses the object, StringBuilder is the right choice. This is the case for local variables, for example, within a method.

Otherwise the classes offer the same methods, which means the API is compatible.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *