logo

CuriousTab

CuriousTab

Discussion


Home Java Programming Garbage Collections See What Others Are Saying!
  • Question
  • 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
  • A. After line 7
  • B. After line 8
  • C. After the start() method completes
  • D. When the instance running this code is made eligible for garbage collection.

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

    Explanation
    Option D is correct. By a process of elimination.

    Option A is wrong. The variable d is a member of the Test class and is never directly set to null.

    Option B is wrong. A copy of the variable d is set to null and not the actual variable d.

    Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference.


  • More questions

    • 1. What will be the output of the program?
      class Super
      { 
          public int i = 0; 
      
          public Super(String text) /* Line 4 */
          {
              i = 1; 
          } 
      } 
      
      class Sub extends Super
      {
          public Sub(String text)
          {
              i = 2; 
          } 
      
          public static void main(String args[])
          {
              Sub sub = new Sub("Hello"); 
              System.out.println(sub.i); 
          } 
      }
      

    • Options
    • A. 0
    • B. 1
    • C. 2
    • D. Compilation fails.
    • Discuss
    • 2. What will be the output of the program (in jdk1.6 or above)?
      public class BoolTest 
      {
          public static void main(String [] args) 
          {
              Boolean b1 = new Boolean("false");
              boolean b2;
              b2 = b1.booleanValue();
              if (!b2) 
              {
                  b2 = true;
                  System.out.print("x ");
              }
              if (b1 & b2) /* Line 13 */
              {
                  System.out.print("y ");
              }
              System.out.println("z");
          }
      }
      

    • Options
    • A. z
    • B. x z