Java OCA OCP Practice Question 168

Question

Given:

public class Main { 
  Main(int x, Main n) { 
    id = x; //  w w w . ja v a  2 s  .c o  m
    p = this; 
    if(n != null) p = n; 
  } 
  int id; 
  Main p; 
  public static void main(String[] args) { 
    Main n1 = new Main(1, null); 
    n1.go(n1); 
  } 
  void go(Main n1) { 
    Main n2 = new Main(2, n1); 
    Main n3 = new Main(3, n2); 
    System.out.println(n3.p.p.id); 
  } 
} 

What is the result?

  • A. 1
  • B. 2
  • C. 3
  • D. null
  • E. Compilation fails


A is correct.

Note

Three Main objects are created.

The n2 object has a reference to the n1 object, and the n3 object has a reference to the n2 object.

The S.O.P. can be read as, "Use the n3 object's Main reference (the first p), to find that object's reference (n2), and use that object's reference (the second p) to find that object's (n1's) id, and print that id."




PreviousNext

Related