Sunday, 13 December 2015

What is String, String Buffer,String Builder and it's differnce

String :

 - String is immutable(once object is created can not be changed)
- String in Java is not a primitive data type like int, long or double
 - String is final
 Ex: String str="abc";
 Why String is Immutable or Final in Java
 - String is Immutable in Java because String objects are cached in String pool.

String Buffer:
 - String Buffer is mutable means one can change the value of object.
 - The object created through stringbuffer is stored in the heap.
  - string buffer is thread safe
 - Ex: StringBuffer demo1=new Stringbuffer("hello");
demo1=new StringBuilder("Bye");/vaule changed
StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.

Ex:
public class Test{

    public static void main(String args[]){
       StringBuffer sBuffer = new StringBuffer(" test");
       sBuffer.append(" String Buffer");
       System.out.println(sBuffer);
   }
}


String builder:
 - String builder is also mutable means one can change the value of object.
 - The object created through stringbuilder is stored in the heap.
 - Stringbuikder is not thread safe
 - StringBuilder demo2=new StringBuilder("HIIII");
demo2=new StringBuilder("Bye");//value changed
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously

----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)             Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast






No comments:

Post a Comment