Monday, 10 February 2014

Difference Between String and String Buffer

String & StringBuffer,both are used to represent the sequence of characters.How ever there is some difference between them
Strings:
     Immutable:-When You perform any write operation on existing String object,a new object will be created, the modification is done there,and that object will be returned to you.The old object will loose the reference and hence garbage collected later.
   String Pool:-It supports String Pool concepts.So you can write String str=”Hello”;
Performance:-Low performance,due to unnecessary object created
overriding:-Strings class has overrided equals() from object class,equals() checks for content equality
StringBuffers: 
mutable:-When you perform any write operation on existing StringBuffer object,new object will not
                           be  created and same object will be modified
String Pool:-It doesnot support String pool concepts.So you cannot write StringBuffer strBuff=”Hello”;
Performance:-High Performance
Overriding:-This class has not overrided equals().so equals() will still compare for reference equality
When to use String and StringBuffer:
If your code demands you to write the logic,where string object will be modified continuously,then better use StringBuffer,to avoid unnecessary object creation
If you want to enjoy string pool,and are sure string wont be modified much,use String.The following Example Demonstate the same
StringDemo.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class StringDemo
{
    public static void main(String args[])
    {
        String str="satya";
        System.out.println(str+"::"+str.hashCode());
        str=str+"tech";
        System.out.println(str+"::"+str.hashCode());
 
        //StringBuffer strBuff="java";  //invalid
        StringBuffer strBuff=new StringBuffer("java");
        System.out.println(strBuff+"::"+strBuff.hashCode());
 
        //strBuff=strBuff+"tech";  //invalid
        strBuff.append("tech");
        System.out.println(strBuff+"::"+strBuff.hashCode());
    }
}//class
O/p:-
satya::109209966
satyatech::1016445692
java::4384790
javatech::4384790
Note:-See the hashCode of first 2 line.We have modified the String,but new Object was created,so different hashCode
The last 2 hashCode remains the same,Since we had used StringBuffer.
HashCode:-It is a hexadecimal representation of Memory Location

No comments:

Post a Comment