Originally posted by mukki pandey:
public class Stngcheck {
/**
* @param args
*/
public static void main(String[] args) {
Stngcheck ss = new Stngcheck();
String s1="1";
String s2="2";
s2=s1;
System.out.println(s2);
ss.go(s2);
}
public void go(String s3){
System.out.println(s3);
}
}
Hi Javaranchers
since string is immutable object why does s2 prints 1 i know this is pretty silly but i want to know pleaseeeeee
Hi,
One important thing we need to remember is String objects are immutable;String references are not.
In the above example,
s2=s1;
s2 reference is changed to point to another object which s1 points to("1").The object which s2 used to refer to "2" is still there but not reachable(abandoned).So the String objects are as such immutable.
It will be more clear if you could just draw a picture.
This pictorial representation is very helpful for solving gc problems too.Trust me.When I started learning this concept,I just tried to solve mentally but couldnt get it.Thats when I started using diagrams.
Moreover the String immutability is also shown by pictorial representation in K&B book.Please go over this chapter once again.I am sure You can get it.
O..another thing.No question is silly.I have asked sillier questions before.Always there will be a patient someone to answer these questions.so dont worry.
hope this helps.
[ October 18, 2008: Message edited by: sumi rankan ]