Question : How may Objects are created within main(), how many are eligible for garbage collection?
I am preparing for SCJP exam and I was going thru this garbage collection Q and I am not sure what is correct. Can some help me with this question?
The book's answer is five object were created and two are eligible for GC. still don't understand how?
The class Dozens contains an int array, which is an object. Therefore every time you create a Dozens object two objects are created (one instance of Dozens, which again contains one instance of an int array).
creates one object which is an array capable of containing three instances of type Dozens.
creates a Dozens object (so two objects including the int array contained in Dozens).
again creates a Dozens object (and therefore two objects altogether).
just makes the variable da referring to an existing Dozens object.
Five objects were created then.
d and d both refer to the same object so
make one Dozens object eligible for GC. As it contains the int array two objects are eligible for GC altogether.
Hope that is right.
Joined: Nov 23, 2011
Thank you John for answering my question. But I am still confused.
1.Dozens  da = new Dozens; When Dozens object is created, two objects are created? one is Dozens array and second is an int array which is in Dozens class? So, total 2 Objects so far.
2.da = new Dozens(); //one object created So, total 3 objects created
3.Dozens d = new Dozens(); // one object created. So, total 4
4.da = d; // this is actually referencing to the created object so no object is created here Right..! correct me please if i m wrong. //so total four objects are created
this is what i understood. I know this is wrong but whould you mind give me some more explanation?
Joined: Jul 19, 2011
No Dozens object is created here. It is an array which can hold three Dozens objects. So one object created here.
With each new two objects are created (a dozens object containing an array object). So four objects created. That's five objects overall.
The point is that only creates one object, whereas creates two objects.
Joined: Nov 23, 2011
ooh. Thanks John got the point forever...! Great explanation...!