Hi I am reviewing for scjp just want to clarify a question I've encountered regarding eligibility of Garbage Collection.
Here's the code:
When // doStuff is reached, how many objects are eligible for GC?
D. Compilation fails
E. It is not possible to know
F. An exception is thrown at runtime
® ✓ C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short
wrapper object that is also eligible.
®˚ A, B, D, E, and F are incorrect based on the above. (Objective 7.4).
My Question is , in this line CardBoard c3 = c1.go(c2); ====> c3 becomes null right? so should also be eligible for GC?
Hi I have another part of the mock exam to clarify, Hope you dont mind.
Here is the code:
When line 16 is reached, how many objects will be eligible for garbage collection?
® ✓ B is correct. It should be clear that there is still a reference to the object referred to by
a2, and that there is still a reference to the object referred to by a2.b2. What might be
less clear is that you can still access the other Beta object through the static variable
a2.b1—because it's static.
®˚ A, C, D, E, and F are incorrect based on the above. (Objective 7.4)
My Question: For what I understand
This line of codes creates 4 objects:
---->Beta b1 = new Beta(); Beta b2 = new Beta(); Alpha a1 = new Alpha(); Alpha a2 = new Alpha();
and this line of codes puts a1,b1 and b2 to be eligible for GC
as i could evaluate this code only those objects are eligible for garbage collection which cant be referenced by any code in program.
so as in your question a1=null really makes the obj unreachable but after making b1 and b2 null the objects referenced by them can still be referenced as follows b1 can be referenced by class name Alpha.b1 because its static, and for b2 we will have to look for a2 since a2 is not made null so we can still access b2 with the help of a2.b2
hope this helps
Correct me if i am wrong
Joined: Oct 26, 2009
Thank You for the Reply By the Way,
I Think Im getting it, Correct me if I am wrong, Here's what I think happen.
This line creates 4 Objects on the heap
Then the following line:
And then the following line:
Therefore a1 only is eligible for Garbage Collection because the object created by b1 and b2 are also "Pointed by static Beta and Beta in class Alpha"
Please Correct me if I am wrong.
Thank You for your help Mahesh chitale ,Minhaj kaimkhani and Raju Champaklal !