Java OCA OCP Practice Question 679

Question

In the following code, after which statement (earliest), the object originally held in s, may be garbage collected ?

1. public class Main{ 
2.   public static void main  (String args []){ 
3.      Student s = new Student ("Tom", "001"); 
4.      s.grade (); //  www . ja v  a  2  s  .  c  o m
5.      System.out.println (s.getName ()); 
6.      s = null; 
7.      s = new Student ("Tom", "001"); 
8.      s.grade (); 
9.      System.out.println (s.getName ()); 
10      s = null; 
      } 
    } 

public class Student{ 
   private String name, rollNumber; 
    
   public Student (String name, String rollNumber)  { 
      this.name = name; 
      this.rollNumber = rollNumber; 
    } 

   //valid setter and getter for name and rollNumber follow 

   public void grade ()  { 
    } 

} 

Select 1 option

  • A. It will not be Garbage Collected till the end of the program.
  • B. Line 5
  • C. Line 6
  • D. Line 7
  • E. Line 10


Correct Option is  : C

Note

Since there is only one reference to Student object, as soon as it is set to null, the object held by the reference is eligible for GC, here it is done at line 6.

Although an object is created at line 7 with same parameters, it is a different object and it will be eligible for GC after line 10.




PreviousNext

Related