Gadgets

Sunday, 20 December 2015

Difference between String,StringBuffer, and StringBuilder

Difference between String and StringBuffer ?
====================================
=>String is Immutable (non changeable) and StringBuffer is Mutable (changeable)
=>String:-
=========
Once we create a String Object then we can’t perform any changes on that Object. If we are trying to perform any changes on that Object, then it will create a new Object
String s=new String("java");
s.concat("technology");
Output:- java
We can't perform concat operation on same object "s". 
------------------------------------------------------------------------------------
String s=new String("java");
String s1=s.concat("technology");
Output:- output is "javatechnology" and it store in new String Object "s1". But we can't perform concat operation on same object "s". 
=>StringBuffer:-
==============
Once we create a StringBuffer Object then we can perform any changes on that Object.
StringBuffer sb=new StringBuffer("java");
sb.append("technology");
Output:- javatechnology

public class Test {
   public static void main(String arg[])
   {
   String s=new String("java");
   s.concat("technology");
   System.out.println("String..."+s);
  
   StringBuffer sb=new StringBuffer("java");
   sb.append("technology");
   System.out.println("StringBuffer..."+sb);
   }
}
/*
Output:
String...java
StringBuffer...javatechnology
*/
Difference between StringBuffer and StringBuilder ?
StringBuffer:-
===========
=>It is synchronized i.e. thread safe. That mean two threads can’t perform operations on StringBuffer simultaneously.
StringBuilder:-
=============
=>StringBuilder is same like StringBuffer, but the difference is StringBuilder is non synchronized i.e, not thread safe. so two threads can perform operations on StringBuilder simultaneously.

public class Test {
   public static void main(String arg[])
   {
       StringBuffer sb=new StringBuffer("java");
       long time=System.currentTimeMillis();
       for(int i=0;i<=10000;i++)
       {
       sb.append("tech");
       }
       System.out.println("if synchronized time taken..."+(System.currentTimeMillis()-time)+"ms");
      
       StringBuilder s=new StringBuilder("java");
       time=System.currentTimeMillis();
        for(int i=0;i<=10000;i++)
       {
       s.append("tech");
       }
       System.out.println("if non-synchronized time taken..."+(System.currentTimeMillis()-time)+"ms");
      
   }
}
/*
Output:
if synchronized time taken...4ms
if non-synchronized time taken...1ms

*/

1 comment: