This content has been marked as final. Show 4 replies
Won't s2 be affected (it is not getting affected actually..)
s1 is a variable. It holds a value. That value is a reference, which points to a particular String object.
s2 is a variable. It holds a value. That value is a reference, which points to a particular String object. It is the same object that s1 points to.
When you do s1 = null, or, for that matter, s1 = anything, all that does is change the reference value that s1 holds. It does not change any object. It does not affect any other variable that happens to hold the same reference value as s1.
If I have a piece of paper called s1, and I write the address of your house on it, and I have another piece of paper that I call s2, and I read the address on s1 and copy it onto s2, and then I erase what's on s1, it does not change what's on my s2 paper--it still has the address of your house written on it--and it does not change the contents of your house.
amtidumpti wrote:No. In your model here, a variable's value is a String object. It's as if your entire house exists on my s1 paper, and an exact duplicate house with all the same contents exists on my s2 paper. In Java, no variable or expression ever holds an object. No value is ever an object.
So is it something like ....
Variable Memory Address Value s1 0234234 "Java" s2 0234235 "Java" is s1 is set to null : Variable Memory Address Value s1 0234234 null s2 0234235 "Java"
It's more like this:
and 11223344 is, roughly speaking, the "address" where the String object holding "Java" is stored.
Variable Memory Address Value s1 0234234 11223344 s2 0234235 11223344 is s1 is set to null : Variable Memory Address Value s1 0234234 null s2 0234235 11223344
And in both your model and mine, "Memory Address" is not the address that the variable holds. Rather, it is the address that corresponds to what we humans have named s1 and s2 for our convenience.
Edited by: jverd on Apr 10, 2009 11:43 AM