This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
There is this question in chapter 3 of scjp 6 study guide book
The question is:
which are true about objects created in the main() and eligible for Garbage Collection:
class Dozens{
int[] dz={1,2,3,4,5,6,7,8,9,10,11,12};
}
public class Eggs{
public static void main(String[] args){
Dozens[] da= new Dozens[3];
da[0]=new Dozens();
Dozens d=new Dozens();
da[1]=d;
d=null;
da[1]=null;
//line 14
}
}
In the book the answers are five objects are created and this i understand and the other answer is two objects are eligible for the GC
In the explanation it says the two objects are da[1] and it array which is dz.
what i don't understand is why isn't Object 'd' included in the GC because i see it referenced to null
Leandro Coutinho
Ranch Hand
Joined: Mar 04, 2009
Posts: 415
posted
0
d is not an object. it is a reference variable.
da[1] is refering to the same object as d.
when d = null; da[1] still is referencing the object.
when da[1] = null then the object don't have more references.
dz still has a reference, but it is isolated, then it can be garbage collected.
at first an array object da lets say o1
da[0]--------->dozen obj+ array obj 2 objects lets say o2 & o3
d ------------->dozen obj +array obj 2 object lets say 04 & o5
da[1] -----------------^ no new objects
d=null no object is eligible
da1[1] = null o4 & o5 are eligible
hence
five objects were created
at line 14 two are eligible for gc
solve the problem by creating a heap i can't show you the one i created for it