Sunday, 13 November 2011

Sun Certified Java Programmer (SCJP)

How many objects will be eligible for garbage collection after line 7?


public class TutorialGC
{


public static void main(String [] args)
{


Object a = new Integer(100);   // Line1
Object b = new Long(100);       // Line2
Object c = new String("100");  // Line3
a = null;                                        // Line4
a = c;                                             // Line5
c = b;                                             // Line6
b = a;                                             // Line7
// Rest of the code here


}


}



Choices:



  • A. 0

  • B. 1

  • C. 2

  • D. 3

  • E. Code does not compile


Correct choice:



  • B


Explanation:


Among the three objects created in lines 1, 2, and 3, only the Integer object is eligible for garbage collection at the end of line 7. The reference variable a, which originally referred to the Integer object is made to refer to the String object in line 5. So the Integer object is eligible for garbage collection after line 5, since there are no variables referring to it. The variables b and c refer to the String and Long objects in lines 6 and 7, so they are not eligible for garbage collection.


No comments:

Post a Comment