Originally posted by Gagan Sabharwal: SCJP(K&B)question 2,Self Test, chapter 3 -Assignments
How many objects are elligible for garbage collection?
The answer is the second option.But i am unable to understand the reason for it.
At line 1 one object is created (let me call it obj1) so c1---> obj1 similarly at line 2 c2-->obj2
Number of CardBoard objects created after execution of line 2 = 2.
At line 3 1. There is only one reference, c3. No object. 2. We are passing the value of c2's reference to method local cb at line 4. i.e cb also refers obj2 so on total we have two objects and three reference, c1--> obj2 c2-->obj2 cb-->obj2 further, c1 and c2 are local to main() and cb is local to go().
At line 5, cb-->null c1--> obj2 c2-->obj2 cb-->null
Remember c2 is still pointing to obj2.
cb which is null is returned and assigned to c3.
At line 3 1. cb no more exists, as it is local to only go(). 2. c3-->null
At this point c1-->obj1 c2-->obj2 c3-->null
line 7, c1 = null. i.e. c1--> null, so obj1 is freed and is not being pointed by anything, victim of garbage collection? yes. But just one small thing with obj1, it has an internal 'story' variable which is a wrapper object of type 'Short' (note the capital 'S').
c1 and story are two objects to be wrapped up.! !! [ August 07, 2007: Message edited by: Akhilesh Trivedi ]
Yes, i3 and i4 comparison will be false. So if I understand it correctly, i3 and i4 point to different objects. So if you make them null those Integer objects will be eligible for garbage collection. So in that case, Akhilesh's arguments remain true, assuming the corrected example i.e., story=200. Am I missing something? [ August 09, 2007: Message edited by: Sahid Khan ]
Joined: Jul 17, 2007
I have been reading about wrapper classes. I have a doubt.
Line 1 - It creates a new Integer object Line 2 - The method returns a newly created integer object Line 3 - what does this line do.Object creation?
Help me in understanding this.
Thanks Praveen Sp
Joined: Jun 04, 2007
Originally posted by Sahid Khan: Akhilesh's arguments remain true, assuming the corrected example i.e., story=200.
As I said, it's a very good explanation for the corrected example.
Joined: Jun 27, 2007
oh! ok I thought you said otherwise. any way no issues. thanks for all these thoughtful posts.
Joined: Jun 27, 2007
Line 3 - what does this line do.Object creation?
Yes this line also does create an object. But jvm caches it i.e., some where in your program, if jvm needs to box a primitive int (value 2) again, it will not create a new one. But it will use the same one which has been created in this line. JVM caches this value if it is between -128 and 127, i.e., it can be put in a byte.