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

Output:

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

Output:

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

Output:

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

Pin It on Pinterest

Share This