Qualified variables for garbage collection in Java
I was preparing for ocpjp, and I was trapped in the following mock exam questions:
Whereas:
3. interface Animal { void makeNoise(); } 4. class Horse implements Animal { 5. Long weight = 1200L; 6. public void makeNoise() { System.out.println("whinny"); } 7. } 8. public class Icelandic extends Horse { 9. public void makeNoise() { System.out.println("vinny"); } 10. public static void main(String[] args) { 11. Icelandic i1 = new Icelandic(); 12. Icelandic i2 = new Icelandic(); 12. Icelandic i3 = new Icelandic(); 13. i3 = i1; i1 = i2; i2 = null; i3 = i1; 14. } 15. }
When line 14 is reached, how many objects qualify for the garbage collector?
A. 0
B. 1
C. 2
D. 3
E. 4
F. 6
Their correct answer is e, four objects, but I'm not sure why From my point of view, I2 and its weight will qualify for garbage collection Maybe I missed something, please advise me
Solution
Let's call Icelandic () on line 11 ICEA, line 12 iceb, and so on
After creation
i1 = IceA i2 = IceB i3 = IceC
After I3 = I1
i1 = IceA i2 = IceB i3 = IceA
After I1 = I2
i1 = IceB i2 = IceB i3 = IceA
After I2 = null
i1 = IceB i2 = null i3 = IceA
After I3 = I1
i1 = IceB i2 = null i3 = IceB
So only Icelandic () created in line 12 is left Now, each Icelandic () has a long weight, so ICEA and ICEC are not referenced now, which means that four objects (ICEA, icea.weight, ICEC, ICEC. Weight) can be used for GC
Other questions:
>Args is still args. They do not calculate this problem. Out of range > long weight is not statically declared, so each instance of the class has a weight object