Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5.

A list of differences between StringBuffer and StringBuilder is given below:

Difference between StringBuffer and StringBuilder

No.

StringBuffer

StringBuilder

1)

StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.

StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

2)

StringBuffer is less efficient than StringBuilder.

StringBuilder is more efficient than StringBuffer.

3)

StringBuffer was introduced in Java 1.0

StringBuilder was introduced in Java 1.5

 

StringBuffer Example

BufferTest.java

  1. //Java Program to demonstrate the use of StringBuffer class.  
  2. public class BufferTest{  
  3.     public static void main(String[] args){  
  4.         StringBuffer buffer=new StringBuffer("hello");  
  5.         buffer.append("java");  
  6.         System.out.println(buffer);  
  7.     }  
  8. }  

Output:

hellojava

StringBuilder Example

BuilderTest.java

  1. //Java Program to demonstrate the use of StringBuilder class.  
  2. public class BuilderTest{  
  3.     public static void main(String[] args){  
  4.         StringBuilder builder=new StringBuilder("hello");  
  5.         builder.append("java");  
  6.         System.out.println(builder);  
  7.     }  
  8. }  

Output:

hellojava

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.

ConcatTest.java

  1. //Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.  
  2. public class ConcatTest{  
  3.     public static void main(String[] args){  
  4.         long startTime = System.currentTimeMillis();  
  5.         StringBuffer sb = new StringBuffer("Java");  
  6.         for (int i=0; i<10000; i++){  
  7.             sb.append("Tpoint");  
  8.         }  
  9.         System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
  10.         startTime = System.currentTimeMillis();  
  11.         StringBuilder sb2 = new StringBuilder("Java");  
  12.         for (int i=0; i<10000; i++){  
  13.             sb2.append("Tpoint");  
  14.         }  
  15.         System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
  16.     }  
  17. }  

Output:

Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms