Difference between StringBuffer and StringBuilder

StringBuilder and StringBuffer are used when. the change required or mutability required. Methods are the same constructors are the same.

In StringBuffer Until completing the first thread, other threads have to wait. Exactly the same except one. It is introduced in 1.2v one thread is allowed to operate on String buffer object. performance-wise it's not recommended.

In StringBuilder  performance is high, not synchronized thread safely not required.

 

public class PerformanceTest{  

    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Hello World!!!");  
        for (int i=0; i<100000; i++){  
            sb.append("Welcome");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
        startTime = System.currentTimeMillis();  
          StringBuilder sb2 = new StringBuilder("Hello World!!!"); 
        for (int i=0; i<00000; i++){  
            sb2.append("Welcome");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
    }  
}  
     



 StringBuffer StringBuilder
 1) Every method present in StringBuffer is Synchronised 1) No Method present in StringBuilder is Synchronised
2) At a time only one thread is allowed to operate on StringBuffer object, Hence it is the thread-safe.2)  At a time multiple threads are allowed to operate on StringBuffer object, Hence it is the thread-safe.
3) Increases waiting times for threads, Hence relatively performance is low.3) Threads are not required to wait to operate on the StringBuilder object. Hence relatively performance is high. 
 4) Introduced in 1.0 version 4) Introduced in 1.5 version

We have seen the difference between StringBuffer and StringBuilder. You May interested in difference between String and StringBuffer.