This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I prefer to think of it this way: A reference variable is a piece of paper with latitude/longitude coordinate written on it that tell me where a particular house is. When I pass that variable to a method, I copy the coordinates from my piece of paper onto another piece of paper, and hand that second piece of paper to the method. I have my paper and the method has his, and they both have the same value (the same coordinates) written on them. We can each use our own paper to find the same house.
If he sets his variable to a different value (erases what's on his paper and writes the coordinates of a different house), he's just pointing to a different object. He hasn't change the value of my variable (hasn't changed what's written on my paper) and he hasn't change the state of the object he was pointing to (hasn't changed the furniture or the color of the walls in the house at the original coordinates).
aresh babu wrote:I think totally 3 objects are eligible for garbage collection.
First, note that when we reach the // do stuff line we are still inside the main method, and all of its variables are still in scope.
1. object C3 which is created in main()
There's no object created there. c3 just holds a copy of the reference returned by the go() method. But even if c3 were the only reference to that object, c3 is still in scope, so the object it points to is not GC-eligible.
2. Integer a which is created in go()
3. c3.story because story is also a wrapper object which is created with object c3
No. c3 points to the same value as c2. Both c3 and c2 point to the object created by CardBoard c2 = new CardBoard(); because go() returns a copy of the reference that was passed to it.