Header

Wednesday 4 September 2013

IGNOU BCA 4th sem Solved Assignment - Differentiate String and String Buffer

Differentiate String and String Buffer
Ans
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.

Performance:-Low performance,due to unnecessary object created
overriding:-Strings class has overrided equals() from object class,equals() checks for content equality
mutable:-When you perform any write operation on existing StringBuffer object,new object will not
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
If you want to enjoy string pool,and are sure string wont be modified much,use String.The following Example Demonstate the same
satyatech::1016445692
java::4384790
javatech::4384790
The last 2 hashCode remains the same,Since we had used StringBuffer.


   String Pool:-It supports String Pool concepts.So you can write String str=”Hello”;
StringBuffers: 
                           be  created and same object will be modified
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
StringDemo.java
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
Note:-See the hashCode of first 2 line.We have modified the String,but new Object was created,so different hashCode
HashCode:-It is a hexadecimal representation of Memory Location

No comments:

Post a Comment