What are differences between String and StringBuffer and StringBuilder?

String:The String class is an immutable ,If the content is fixed and won't change frequently then we should go for String

StringBuffer: If the content not fixed and keep on changing and Thread safety is required we should go for StringBuffer,StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.StringBuffer is less efficient than StringBuilder.

StringBuilder:If the content not fixed and keep on changing and Thread safety is not required we should go for StringBuilder,StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.StringBuilder is more efficient than StringBuffer.

  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>
  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>
  13.             sb2.append("Tpoint");  
  14.         }  
  15.         System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
  16.     }  
  17. }  
                   Time taken by StringBuffer: 16ms
                   Time taken by StringBuilder: 0ms