×

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

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.