StringBuilder vs StringBuffer in Java

In our Java Article series, we have already talked about strings a lot of times. A programmer who has just begun programming in Java uses string to print something in the console window. Java provides three classes related to String: String, StringBuffer, and StringBuilder. We all know the famous line System.out.println(“Here we put our String”) that all the java programmers use to print the string on the console.

Many programmers who begin programming in Java don’t know that String is immutable in Java. Every time you perform a change in the String, it results in a new String object creation. Initially, the class that was used to transform the String was StringBuffer but after this Java introduced a new class called StringBuilder. In this article, firstly we will learn about each of these classes and then we will learn StringBuilder vs StringBuffer to understand comparison between StringBuffer and StringBuilder.

Let’s get into the programming paradigm of these classes.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is a StringBuffer Class in Java?

Java StringBuffer class was firstly introduced in Java 1.0v and the principle use of this class was to transform the mutable String. But after introducing the class and using it in multiple threads many problems started arising. This class contains public methods which are Synchronized. The public method that can’t be used at the same time or simultaneously in different threads is known as Synchronized Methods. The only powerful disadvantage of StringBuffer Class is Synchronized Methods. But when using the StringBuffer class, we can ensure the thread safety in our system.

What is a StringBuilder Class in Java?

Java StringBuilder Class eliminates the StringBuffer only because of the multithreading purpose. The StringBuilder class was introduced in Java 1.5v after StringBuffer class having an additional functionality of non-synchronized methods so that multiple threads can be allowed to use StringBuilder objects. This results in the risk of Thread safety if the user runs the same method at many places at the same time. But, the StringBuilder class is more preferable to use as it works efficiently in a multithreaded environment.

Below are some points in which some are common for both the class and some are different.

Parameter StringBuffer StringBuilder
Storage Area Heap Heap
Mutability Yes Yes
Thread Safety Yes No
Speed Very Slow Fast

StringBuilder vs StringBuffer class in Java

StringBuilder vs StringBuffer

1. StringBuffer class was introduced with the introduction of Java but the StringBuilder class was added in Java with the Java 1.5 version.

2. The StringBuffer class is synchronized and contains the synchronized methods like append(), delete(), and insert(). On the other hand, the StringBuilder class is not synchronized.

3. The StringBuffer class ensures thread safety due to the presence of synchronized methods but the StringBuilder is not thread-safe because there are no synchronized methods in the StringBuilder class.

4. If we want to perform String operations in a non-multithreaded environment, then we should use the StringBuilder class and if we want to perform String manipulations in the multithreaded environment, then we should use the StringBuffer class.

5. Since the StringBuffer class has synchronized methods, it performs very slowly as compared to the StringBuilder class.

Most experts prefer to use the StringBuilder class until you are working in a multithreaded environment because it is fast and there is no need to care about thread safety and synchronization while using the StringBuilder class.

S No. StringBuffer Class in Java StringBuilder Class in Java
1. Every String in the StringBuffer object is modifiable i.e. mutable. Every string in the StringBuilder is also modifiable i.e. mutable.
2. Thread safety is provided by StringBuffer public methods. Thread safety can be violated in the StringBuilder public methods
3. Introduced in Java 1.0v Introduced in Java 1.5v
4. At a time StringBuffer objects allow only one thread to use the StringBuffer object which directly affects the thread-safety measures. At a time StringBuilder object allows multiple threads to use the StringBuilder object which directly thread safety and can violate the safety.
5. In this, if multiple threads want to access a single StringBuffer object then they need to wait that affects the relative execution time. In this, if multiple threads want to access a single StringBuilder object then they can use it simultaneously which increases the performance.
6. Performance is very low as compare to StringBuilder Performance is very high in compression with StringBuffer
7. Allocation of the object is in Heap Allocation of the object is also in Heap
8. Example:

class StringBufferDemo

{

    public static void main(String [ ] args)

    {

StringBuffer sbuffer = new StringBuffer(“Tech”);                            sbuffer.append(“vidvan”);

         System.out.println(sbuffer);

    }

}

 

Output:

 

Techvidvan

Example:

class StringBuilderDemo

{

   public static void main(String [ ] args)

   {

StringBuilder sbuild = new     StringBuilder(“Tech”);                    sbuilder.append(“vidvan”);             System.out.println(sbuilder);

    }

}

 

Output:

 

Techvidvan

Code to understand Java StringBuffer vs StringBuilder class:

Performance Program:

package com.techvidvan.stringclasses;
public class PerformanceSpeed {
  public static void main(String[] args) {
    long startingTime = System.currentTimeMillis();
    StringBuffer sbuffer = new StringBuffer("Tech");
    for (int i = 0; i < 1000; i++) {
      sbuffer.append("vidvan");
    }
    System.out.println("Time consumed by StringBuffer: " + (System.currentTimeMillis() - startingTime) + "milliseconds");
    startingTime = System.currentTimeMillis();
    StringBuilder sbuilder = new StringBuilder("Tech");
    for (int i = 0; i < 1000; i++) {
      sbuilder.append("vidvan");
    }
    System.out.println("Time consumed by StringBuilder: " + (System.currentTimeMillis() - startingTime) + "milliseconds");
  }
}

Output:

Time consumed by StringBuffer: 2 milliseconds
Time consumed by StringBuilder: 1 milliseconds

From the above output, we can easily conclude that the StringBuffer takes more time as compared to the StringBuilder class. This output may vary from machine to machine and even the output may be different if you compile it several times.

String to StringBuffer and StringBuilder

package com.techvidvan.stringclasses;
public class Demo {
  public static void main(String[] args) {
    StringBuffer sbuffer = new StringBuffer("TechVidvan");
    StringBuilder sbuilder = new StringBuilder("Java");
    String str1 = sbuffer.toString();
    System.out.println("StringBuffer object to String: ");
    System.out.println(str1);
    String str2 = sbuilder.toString();
    System.out.println("StringBuilder object to String: ");
    System.out.println(str2);
    sbuffer.append(" Tutorial");
    System.out.println("Appending to StringBuffer: " + sbuffer);
    System.out.println("StringBuffer String: " + str1);

  }
}

Output:

StringBuffer object to String:
TechVidvan
StringBuilder object to String:
Java
Appending to StringBuffer: TechVidvan Tutorial
StringBuffer String: TechVidvan

Conclusion

In conclusion, we saw the difference between both the classes related to String which are StringBuffer class and the StringBuilder class. Both are mutable, unlike the String class that is once they are created they can be changed. The only major parameter that differentiates both these classes is the presence of synchronized methods. The StringBuffer is synchronized while the StringBuilder is not synchronized. We can use the StringBuffer class while working in a multithreaded environment. We have discussed StringBuilder vs StringBuffer with examples.

Do rate us at Google to let us know your experience with us.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.