Win a copy of Penetration Testing Basics this week in the Security forum!

# Garbage Colection

Janki Shah
Ranch Hand
Posts: 136

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?

John Stark
Ranch Hand
Posts: 185
• 1
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[1] referring to an existing Dozens object.
Five objects were created then.

d and d[1] 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.

John

Janki Shah
Ranch Hand
Posts: 136
Thank you John for answering my question. But I am still confused.
1.Dozens [] da = new Dozens[3]; 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[0] = new Dozens(); //one object created So, total 3 objects created
3.Dozens d = new Dozens(); // one object created. So, total 4
4.da[1] = 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?

Thanks,
janki

John Stark
Ranch Hand
Posts: 185
• 1
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.

John

Janki Shah
Ranch Hand
Posts: 136
ooh. Thanks John got the point forever...! Great explanation...!

John Stark
Ranch Hand
Posts: 185
Welcome to the ranch

Wu Wen
Greenhorn
Posts: 27

ikneet singh
Greenhorn
Posts: 14
howerver if da[1] = null if omitted and da[1] still has a reference to the object to which d referenced earlier then how many objects will be eligible for gc???

Ankit Garg
Sheriff
Posts: 9540
33
• 1
Ikneet, if we comment this line, then no objects will be eligible for GC

ikneet singh
Greenhorn
Posts: 14
@ankit thanks... ;)