hi,
please check out this example that u wanted. Basically i am creating two string objects a and b first. the
test a==b is true saying both are pointing to the same object. i am replacing a character in a. A new object is created as Strings are immutable. thus a==b test fails now as the two objects are not the same now.
this is not the same with StringBuffer. even though i have appended a character to ab this is reflected in bb also. and the objects pointed to by ab and bb still remain the same.
class demo
{
public static void main(String[] args)
{
// both a and b in the code below point to the same object
String a=new String("hello");
String b=a;
if(a==b){
System.out.println(" a and b are equal");}
else{
System.out.println("false");
}
// a now points to a different object
a=a.replace('h','r');
System.out.println("a is"+a);
System.out.println("b is"+b);
// a is not equal to b as a new object is created
if(a==b){
System.out.println("true");}
else{
System.out.println("false");
}
// case of StringBuffer
StringBuffer ab=new StringBuffer("hello");
StringBuffer bb=ab;
if(ab==bb){
System.out.println("true");}
else{
System.out.println("false");
}
// ab still points to the same object
ab=ab.append('c');
System.out.println(ab);// ab contains helloc
System.out.println(bb);// bb also contains helloc
// ab equal to bb as no new object is created
if(ab==bb){
System.out.println("true");}
else{
System.out.println("false");
}
}
}