Dear friend, String and stringBuffer have a diffrence. -> they say if you declare a Object of String class then the contents of it can not be changed.But that is not the case in StringBuffer.My doubt is that I want a practical example to show that when i declare a string object the contents of it is unchanged and that if i declare a String buffer object its contents can be changed. PLease be brief in giving a solution. awaiting a reply from any intellectual from partha
deekasha gunwant
Ranch Hand
Joined: May 06, 2000
Posts: 396
posted
0
hi parth, this code probably will help u. public class Str { public static void main(String j[]) { String s = new String("hello"); StringBuffer sb = new StringBuffer("Hello");
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"); }