Java OCA OCP Practice Question 343

Question

Which are true of the following code? (Choose all that apply)

1:  import java.util.*; 
2:  public class Main { 
3:  public Main(String n) { 
4:     name = n; //w w  w.j  a v  a  2s. c  o  m
5:  } 
6:  public static void main(String[] args) { 
7:    Main one = new Main("g1"); 
8:    Main two = new Main("g2"); 
9:    one = two; 
10:   two = null; 
11:   one = null; 
12: } 
13:   private String name; } 
  • A. Immediately after line 9, no Main class objects are eligible for garbage collection.
  • B. Immediately after line 10, no Main class objects are eligible for garbage collection.
  • C. Immediately after line 9, only one Main class object is eligible for garbage collection.
  • D. Immediately after line 10, only one Main class object is eligible for garbage collection.
  • E. Immediately after line 11, only one Main class object is eligible for garbage collection.
  • F. The code compiles.
  • G. The code does not compile.


C, D, F.

Note

Immediately after line 9, only Main g1 is eligible for garbage collection since both one and two point to Main g2.

Immediately after line 10, we still only have Main g1 eligible for garbage collection.

Reference one points to g1 and reference two is null.

Immediately after line 11, both Main objects are eligible for garbage collection since both one and two point to null.

The code does compile.

Although it is traditional to declare instance variables early in the class, you don't have to.




PreviousNext

Related