Given the following code, how many objects are created within main() and after the execution of line 15, how many objects are eligible for garbage collection?
class Test
{
int[] dz = {1, 2, 3, 4, 5};
}
public class MarksDriver
{
public static void main(String[] args)
{
Test[] da = new Test[3];
da[0] = new Test();
Test d = new Test();
da[1] = d;
d = null;
da[1] = null; //line 15
//some code
}
}
Ok first of all, Please don't mark it as Homework. This is a question from a test at my college. According to me there should be 2 objects those are created and 1 is eligible for garbage collection after line 15. It's because there are only two new operators used for creating objects and the object that 'd' was referring to at the beginning is lost after line 15 so it will be freed of memory. So I marked the last option that is none of the above. But my Teacher marked it wrong and said the answer is 5,2. She gave some explanation that I didn't get a hint of.
So can anyone explain this?
When we write
Test d = new Test();
2 objects are created one is d other one is member array dz
same way with
da[0] = new Test();
2 objects are created one is stored in da[0] other one is member array dz
and one more object is created by
Test[] da = new Test[3];
so total 5 objects created
with these 2 lines of code there is no reference for one object of class test created at line 13 which makes it eligible for garbage collection which in turn also makes the member array dz eligible for garbage collection, so 2 objects become eligible for garbage collection after line 15
d = null;
da[1] = null;