# Garbage Collection - P274 Kathy Sierra

Harikrishna Gorrepati
Ranch Hand
Posts: 423
Hi, Could you please exaplain where objects created & which objects eligible for GC.

All, I understand is objects are created: dz at line 4, da at line 8 , da[0] at line 9 and d at line 10 : Total 4.
Line 12 making "d" object eligible for GC.

But answer is Five objects created and two are eligible for GC.

3. class Dozens {
4. int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
5. }
6. public class Eggs {
7. public static void main(String[] args) {
8. Dozens [] da = new Dozens[3];
9. da[0] = new Dozens();
10. Dozens d = new Dozens();
11. da[1] = d;
12. d = null;
13. da[1]= null;
14. // do stuff
15. }
16.}

Question: How many objects are created and how many of those are eligible for garbage collection when line
14 is reached?

Abimaran Kugathasan
Ranch Hand
Posts: 2066
Harikrishna Gorrepati, Please => UseCodeTags <= and => SearchFirst <=. This is discussed recently!

Harikrishna Gorrepati
Ranch Hand
Posts: 423
Code is same..Question was different.

Abimaran Kugathasan
Ranch Hand
Posts: 2066
I think, those links will help you to identify the solutions. If not, there are 5 objects created.

1) First - on the 8th line.
2) Second - on the 9th line.
2.1) Third - as the instance of the object created in the 9th line!
3) Fourth - on the 10th line.
4) Fifth - as the instance of the object created in the 10th line!

OK? Now find out how many are eligible for GC~

Harpreet Singh janda
Ranch Hand
Posts: 317
With the creation of 1 Dozens object, 2 objects will be created - 1 is Dozens object itself and secod is the the object for int array inside the Dozens object (remember that array itself is treated as an object) so

1 object at 8th line
2 at 9th line
2 at 10th line

object at 11th line is eing reassigned, so hre no object will be created but the object created at line 10 will have 2 referencs.

Now wou can count the total number of objects created.

Harikrishna Gorrepati
Ranch Hand
Posts: 423
Because of Line 12 and 13 second Dozens object is eligible for GC. But, Why second dz object is also eligible for GC..If second Dozens object is eligible for GC, how does it make second dz[] eligible for GC ?

Abimaran Kugathasan
Ranch Hand
Posts: 2066
Harikrishna Gorrepati wrote:Because of Line 12 and 13 second Dozens object is eligible for GC. But, Why second dz object is also eligible for GC..If second Dozens object is eligible for GC, how does it make second dz[] eligible for GC ?

Dozens object HAS-A array object named as dz. So, if you remove one of Dozens object, then the dz object associated with it will also removed. Did you get it?

Harikrishna Gorrepati
Ranch Hand
Posts: 423
Excellent. I got it. Thanks Abimaran.

Abimaran Kugathasan
Ranch Hand
Posts: 2066
You are Welcome!