Quiz: Garbage Collection

To View Tricks: Login Required

Number of Questions: 13

Question: 11 -

After line 8 runs. how many objects are eligible for garbage collection?

public class X 
{
    public static void main(String [] args) 
    {
        X x = new X();
        X x2 = m1(x); /* Line 6 */
        X x4 = new X();
        x2 = x4; /* Line 8 */
        doComplexStuff();
    }
    static X m1(X mx) 
    {
        mx = new X();
        return mx;
    }
}

Options:
  1. 2

  2. 0

  3. 3

  4. 1

  5. Answer:

    1

    Solution:

    By the time line 8 has run, the only object without a reference is the one generated as a result of line 6. Remember that "Java is pass by value," so the reference variable x is not affected by the m1() method.


Question: 12 -

Where will be the most chance of the garbage collector being invoked?

class HappyGarbage01 
{ 
    public static void main(String args[]) 
    {
        HappyGarbage01 h = new HappyGarbage01(); 
        h.methodA(); /* Line 6 */
    } 
    Object methodA() 
    {
        Object obj1 = new Object(); 
        Object [] obj2 = new Object[1]; 
        obj2[0] = obj1; 
        obj1 = null; 
        return obj2[0]; 
    } 
}

Options:
  1. After line 9

  2. Garbage collector never invoked in methodA()

  3. After line 10

  4. After line 11

  5. Answer:

    Garbage collector never invoked in methodA()

    Solution not available.

Question: 13 -

When is the Demo object eligible for garbage collection?

  
class Test
{
	private Demo d;
	void start()
	{
		d = new Demo();
		this.takeDemo(d); /* Line 7 */
	} /* Line 8 */
	void takeDemo(Demo demo)
	{
		demo = null;
		demo = new Demo();
	}
}

Options:
  1. When the instance running this code is made eligible for garbage collection.

  2. After line 8

  3. After line 7

  4. After the start() method completes

  5. Answer:

    When the instance running this code is made eligible for garbage collection.

    Solution not available.