curve karve wrote:How many objects are eligible for garbage collection after executing line 7?
view source print
public class Tester {
public static void main(String[] args) {
Integer x = new Integer(3000);
Integer y = new Integer(4000);
Integer z = new Integer(5000);
Object a = x;
x = y;
y = z;
z = null; //line 7
}
}here the answer is zero i don know how..anybody kindly explain..according to me the answer should be 3...
Ok, I set up a little graph, lets see if I can recreate it:
Three objects are created. For ease, I call them ojb1, obj2, obj3, in order of creation. Left column is the objects, right is the variable referencing them, through the line Object a = x:
Objects|references
obj1 |x,a
obj2 |y
obj3 |z
Now we assign x the same reference as y, so our graph changes to this:
Objects|references
obj1 |
x,a
obj2 |y,x
obj3 |z
Now we assign y the same reference as z, so our graph changes to the following:
Objects|references
obj1 |
x,a
obj2 |
y,x
obj3 |z,y
Now we assign z null, so our graph changes to the following:
Objects|references
obj1 |
x,a
obj2 |
y,x
obj3 |
z,y
Even though z is pointing to nothing, all created objects have active references. Therefore, none of them are eligible for GC.