I too made a memory map diagram for the same and I conclude that because of a2.a=null and a1=a3 just one object that is a2 is eligible for garbage collection because as a1 and a3 are still being referenced so they are not eligible . am I understanding it correctly?
Can you please tell more specifically which object is eligible for garbage collection and why because by diagram I am able to understand that one object is there which is eligible for it but which one . I guessed is a2. Please clear it.
On line 10
A a2=new A(new A(null)); the object which is created by calling "new A(null)" does not have any reference. So this object will be garbage collected.
Yes only one object is eligible for garbage collection and thats the one referenced by instance member a of object a2 which is afterwards made to null.
This is another example of garbage collection from ExamLab
Class A{
A aob;
public static void main(String args[]){
A a=new A();
A b=new A();
A c=new C();
A.aob=b;
b.aob=a;
c.aob=a.aob;
A d=new A().aob=new(A);
c=b;
c.aob=null;
system.gc();
}
}
How many objects are eligible for garbage collection and which are they ?
I tried to solve this question and conclude that object c and d will be eligible for garbage collection. Please correct me if I am wrong.