Java OCA OCP Practice Question 1406

Question

How many objects are eligible for garbage collection at the end of the main() method?

package mypkg; //from   w  w  w . j a v  a2 s. c  o m
public class Main { 

   static String s1 = new String("A"); 
   static String s2 = new String("B"); 

   public static void m() { 
      String s3 = new String("C"); 
      s2 = s1; 
      s1 = s3; 
   } 

   public static void main(String... args) { 
      m(); 
   } 
} 
  • A. None
  • B. One
  • C. Two
  • D. Three
  • E. The code does not compile.


B.

Note

While s3 goes out of scope after the m() method, the String "C" object is referenced by s1 and therefore cannot be garbage collected.

The string A object is now referenced by s2.

No variables reference the String "B" object, so it is eligible to be garbage collected, and Option B is correct.




PreviousNext

Related