IT Certificaions

Sunday, October 23, 2011

SCJP 6 Questions: Garbage collection

Qu1. See the code ...

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.            // more code
15.       }
16.  }

Which two are true about the objects created within main(), and eligible for garbage collection
when line 14 is reached?

A. Three objects were created
B. Four objects were created
C. Five objects were created
D. Zero objects are eligible for GC
E. One object is eligible for GC
F. Two objects are eligible for GC
G. Three objects are eligible for GC

Answer:  C and F are correct. 

Explanation: When you compile and run,  main method from Eggs runs and object creation starts from line 8. It is first object which is a 1 D array object created.

Now at line 9, Dozens() class no-arg constructor calls and two objects created,
(i) first Class Dozens object  and (ii) integer array type referenced by dz

Similarly at Line 10, you again called new Dozens(), so again there will be two objects like line 9.

Hence total objects created:  Five

Now come to line 11, where you are refering da[1] to the obhect of type Dozen which is already refered by d.

so when you set d=null , da[1] still refer to same object. And finally at Line 13 when you do da[1]=null, here  second Dozens object (and its "int array" object) are not reachable.

So objects eligible for garbage collection: two 

See the figure....

No comments:

Post a Comment