String vs StringBuffer vs StringBuilder in Java

Free Java courses with 37 real-time projects - Learn Java

We know that by default strings are immutable in nature. However, there are many restrictions in an immutable string, when it comes to string handling. That is why Java provides us with two classes, StringBuffer and StringBuilder, that helps programmers take a mutable string as input and work with them. There are pros and cons to both these classes, and it is necessary to know which one to use and when. In this article, we will see StringBuffer vs StringBuilder in detail.

StringBuffer Class in Java:

The StringBuffer class was introduced into the Java Programming Language with Java 1.0v. This class was introduced for the sole purpose of transforming a string into a mutable object. But there arose a problem while using this class in a multi-thread environment.

The methods in this class are public and synchronized, so naturally, they cannot be used simultaneously in multiple threads. This was the main disadvantage of using StringBuffer. But the StringBuffer class also ensures thread safety.

Code to explain Java StringBuffer Class:

package com.DataFlair.Stringbuffer;
public class Append
{
    public static void main(String args[])
    {  
        StringBuffer str=new StringBuffer("Data");  
        str.append("Flair");  
        System.out.println(str);
    }  
}  

The output of the above code:

DataFlair

StringBuilder class in Java:

To put it in simple words, the StringBuilder class was introduced in the Java 1.5v update to replace the StringBuffer class.

The StringBuilder class solves the problem of Multithreading easily. It contains an additional provision of non-synchronized methods which gives it compatibility to run in a multi-thread environment.

Although the StringBuilder class works efficiently in a multi-thread environment, it comes at a risk of thread safety. But programmers still prefer the StringBuilder class over the StringBuffer Class.

Code to understand Java StringBuilder class:

package com.DataFlair.StringBuffervsStringbuilder;
public class Append
{
    public static void main(String args[])
    {  
        StringBuilder str=new StringBuilder("Data");  
        str.append("Flair");  
        System.out.println(str);
    }  
}

The output of the above code:

DataFlair

Summarization of a few important points regarding StringBuffer and StringBuilder:

ParameterStringBufferStringBuilder
Storage AreaHeapHeap
MutabilityYesYes
Thread SafetyYesNo
SpeedVery SlowFast

Difference between StringBuilder vs StringBuffer in Java:

1. StringBuffer class was present right from the beginning when Java was introduced. The StringBuilder class was introduced with version 1.5 update to compensate for the mistakes made in the StringBuffer class.

2. The methods present in the StringBuffer class, like append(), delete(), replace(), etc are synchronized in nature. Whereas the same methods of the StringBuilder class are non-synchronized.

3. The synchronized methods of the StringBuffer class provides thread safety but the StringBuilder class has non-synchronized methods and so it’s not thread-safe.

4. To perform string manipulation in a multi-threaded environment we should use the StringBuilder class, but if there is no multi-threaded environment involved, then StringBuffer can be better due to thread safety.

5. The StringBuilder class is way faster than the StringBuffer class, as synchronization is not required in it.

Even though the StringBuffer is thread-safe, programmers still prefer the StringBuilder as it is way faster.
Let us summarize the differences and similarities into a table:

SL.No.StringBuffer Class in JavaStringBuilder Class in Java
1The strings in the StringBuffer class are always mutable.The strings in the StringBuilder class are also always mutable.
2It is thread-safeIt is not thread-safe.
3Present from Java 1.0Introduced in Java 1.5
4It can use only one thread at a time, thus always ensuring thread safety.It can use multiple threads at a time, and may or may not violate thread safety.
5If multiple threads have to be used, they need to wait for synchronization, thus adding a lot of time to execution. Multiple threads can operate together without synchronization, thus working a lot faster.
6Performance is very lowPerformance is High
7The object is allocated heap memory.The object is allocated heap memory.

Code to understand the performance of Java StringBuffer and StringBuilder:

package com.DataFlair.StringBuffervsStringbuilder;
public class PerformanceAnalysis
{
        public static void main(String[] args)
        {  
                long startTime = System.currentTimeMillis();  
                StringBuffer str1 = new StringBuffer("DataFlair");  
                for (int i=0; i<10000000; i++)
                {  
                    str1.append("StringBuffer");  
                } 
                System.out.println("Time taken by StringBuffer in Millisecond is: " + (System.currentTimeMillis() - startTime) + "millisec"); 
                startTime = System.currentTimeMillis();  
                StringBuilder str2 = new StringBuilder("DataFlair");  
                for (int i=0; i<10000000; i++)
                {  
                    str2.append("StringBuilder");  
                }  
                System.out.println("Time taken by StringBuilder in Millisecond is: " + (System.currentTimeMillis() - startTime) + "millisec"); 
        } 
}

The output of the above code:

Time taken by StringBuffer in Millisecond is: 343millisec
Time taken by StringBuilder in Millisecond is: 316millisec

We can clearly see that the StringBuilder is Faster than the StringBuffer class. The greater the number of operations the greater will be the difference in time.

The time to execute the program depends on the performance of the machine on which it runs.

Code to convert StringBuilder and StringBuffer object to String in Java:

package com.DataFlair.StringBuffervsStringbuilder;
public class Conversion
{
     public static void main(String[] args) {
    StringBuffer str1 = new StringBuffer("DataFlair");
    StringBuilder str2 = new StringBuilder("StringBuffer vs StringBuilder");
    String str1C = str1.toString();
    System.out.println("StringBuffer object to String: ");
    System.out.println(str1C);
    String str2C = str2.toString();
    System.out.println("StringBuilder object to String: ");
    System.out.println(str2C);
  }
}

The output of the above code:

StringBuffer object to String:
DataFlair
StringBuilder object to String:
StringBuffer vs StringBuilder

Conclusion:

In this article, we saw how StringBuilder and StringBuffer have similarities and differences of their own. It is the work of the programmer to understand the situation and implement the better of the two classes for the purpose of the program. We discussed, in brief, the two classes and when to use them with regard to the environment of the system.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

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