Search Your Topic

config
Monday, 24 July 2017 04:27

Difference between StringBuffer and StringBuilder

Written by
Rate this item
(0 votes)

There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below:

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.

StringBuffer Example

 
  1. public class BufferTest{  
  2.     public static void main(String[] args){  
  3.         StringBuffer buffer=new StringBuffer("hello");  
  4.         buffer.append("java");  
  5.         System.out.println(buffer);  
  6.     }  
  7. }  
hellojava

StringBuilder Example

 
  1. public class BuilderTest{  
  2.     public static void main(String[] args){  
  3.         StringBuilder builder=new StringBuilder("hello");  
  4.         builder.append("java");  
  5.         System.out.println(builder);  
  6.     }  
  7. }  
hellojava

Performance Test of StringBuffer and StringBuilder

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

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

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.

Java Training

Facebook