class I {
private I other;
public void other(I i) {other = i;}
}
class J {
private void m1() {
I i1 = new I(), i2 = new I();
I i3 = new I(), i4 = new I();
i1.other(i3); i2.other(i1);
i3.other(i2); i4.other(i4);
}
public static void main (
String[] args) {
new J().m1();
}}
Which object is not eligible for garbage collection after method m1 returns?
a. i1
b. i2
c. i3
d. i4
e. Compile-time error
f. Run-time error
g. None of the above
I answered for the above question as (d) i4. But the answer and explanation given was
(g) None of the above
Explanation:
Please note that this question asks which object is NOT eligible for garbage collection after method m1 returns. The objects referenced by i1, i2 and i3 form a ring such that each object is referenced by another. Even so, nothing outside of method J.m1 references any of those objects. When method J.m1 returns, the ring becomes an island of isolated objects that are not reachable by any part of the user program. A key point to remember is that an object that is referenced by another object can be eligible for garbage collection if the two objects form an island of isolated objects.
Nothing has been explained about i4, some one please explain.
Code:
class I {
private I other;
protected void finalize() throws Throwable{
System.out.println(other);
}
public void other(I i) {other = i;}
}
class J {
private void m1() {
I i1 = new I(), i2 = new I();
I i3 = new I(), i4 = new I();
i1.other(i3); i2.other(i1);
i3.other(i2); i4.other(i4);
}
public static void main (String[] args) {
new J().m1();
System.gc();
}}
//output:
/*
I@1ac04e8
I@765291
I@26e431
I@14f8dab
*/
Does this mean all the four objects are garbage collected?. Isn�t �i4.other(i4)� is still having a reference to the method.