×

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder

StringBuffer

The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences.

Java StringBuffer program

FileName: StringBufferExample.java

 // A basic program that demonstrates the working of StringBuffer
public class StringBufferExample
{ 
// main method
public static void main(String[] argvs)
{ 
    // creating an object of the class StringBuffer
    StringBuffer sb = new StringBuffer("Hi "); 
    // appending the string Tutorial & Example
    sb.append("Tutorial & Example "); 
    // displaying the output
    System.out.println(sb); 
} 
}  

Output:

Hi Tutorial & Example

StringBuilder

The StringBuilder class is also used to create mutable string. The StringBuilder is same as the StringBuffer class. The difference is StringBuilder class is not synchronized whereas the StringBuffer class is synchronized

Java StringBuilder Program

FileName: StringBuilderExample.java

 // A basic program that demonstrates the working of StringBuilder
public class StringBuilderExample
{ 
// main method
public static void main(String[] argvs)
{ 
    // creating an object of the class StringBuffer
    StringBuilder sb = new StringBuilder("Hi "); 
    // appending the string Tutorial & Example
    sb.append("Tutorial & Example "); 
    // displaying the output
    System.out.println(sb); 
} 
}  

Output:

Hi Tutorial & Example

Difference Between StringBuffer and StringBuilder

The following table describes the key differences between StringBuffer and StringBuilder in Java.

StringBufferStringBuilder
StringBuffer is a mutable, thread-safe, and synchronized. Thread-safe means two or more than two threads are not allowed to access the same method of the StringBuffer class simultaneously.StringBuilder class is also a mutable but it is not thread-safe and not synchronized. Thread-safe means two or more than two threads are allowed to access the same method of the StringBuilder class simultaneously.
StringBuffer is not that much efficient as compared to StringBuilder.StringBuilder performs better, i.e., more efficient as compared to StringBuffer.

Performance Comparison Between StringBuffer and StringBuilder class


We know that StringBuilder is quick as compared to StringBuffer. Let’s check it with the help of a Java program.

FileName: PerformanceTestExample.java

 // A basic Java program that compares the performance of StringBuffer and 
// StringBuilder
public class PerformanceTestExample
{ 
// main method
public static void main(String argvs[])
{ 
long sTime = System.currentTimeMillis();
// creating an object of StringBuffer
StringBuffer strBuffer = new StringBuffer("Hi "); 
for (int j = 0; j < 10000; j++)
{ 
     // doing the concatenation work
    strBuffer.append("Tutorial & Example"); 
}
// displaying the time taken by StringBuffer
System.out.println("Total Time consumed by the StringBuffer is: " + (System.currentTimeMillis() - sTime) + "ms"); 
// resetting the start time
sTime = System.currentTimeMillis();
// creating an object of StringBuilder
StringBuilder strBuilder = new StringBuilder("Hi "); 
for (int j = 0; j < 10000; j++)
{ 
     // doing the concatenation work
    strBuilder.append("Tutorial & Example"); 
} 
// displaying the time taken by StringBuilder
System.out.println("Total Time consumed by the StringBuilder is: " + (System.currentTimeMillis() - sTime) + "ms");
} 
}  

Output:

 Total Time consumed by the StringBuffer is: 4ms
Total Time consumed by the StringBuilder is: 3ms 

Explanation: Observe the output, we see that StringBuilder is quicker as compared to StringBuffer.


Related Topics

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.