• Status: Solved
• Priority: Medium
• Security: Public
• Views: 1873

# SCJP question:how many objects are eligible for the garbage collector

``````   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 are eligible for the garbage collector?
I dint understand the concept of how to calculate the objects that are eligible for the garbage collector?can somebody explain it??
``````
0
chaitu chaitu
1 Solution

Analyst ProgrammerCommented:
0

Commented:

This is a good experiment - small program
which shows that indeed both i1 and i3 point at second object
at line 14:

``````public class GCCheck {
}
interface Animal { void makeNoise(); }
class Horse implements Animal {
Long weight = 1200L;
public void makeNoise() { System.out.println("whinny"); }
}
class Icelandic extends Horse {
int i;
public void makeNoise() { System.out.println("vinny"); }
public static void main(String[] args) {
Icelandic i1 = new Icelandic(1);
Icelandic i2 = new Icelandic(2);
Icelandic i3 = new Icelandic(3);
i3 = i1; i1 = i2; i2 = null; i3 = i1;
System.out.println("i1 " + i1);
System.out.println("i2 " + i2);
System.out.println("i3  " + i3);

}
Icelandic(int i){
this.i = i;

}

public String toString() {
return (i + "");
}

}
``````

Output:

``````i1 2
i2 null
i3  2
``````
0

Author Commented:
When line 14 is reached, how many objects are eligible for the garbage collector?
0

Commented:
four are eliegible becuae
alos long value inside which can be GC'ed when the enclosing object disappears,
- so the total will be four which are eligible
0

Analyst ProgrammerCommented:
As quoted from my link, it should be 4.
0

Commented:
Icelandic originally pointed by i1 i1 and long weight inside it are eligivble for GC
Iclendic  originally pointed by i3 and long weight inside it are eligible for GC

So the total will be 4 objects are eligible
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.