Java OCA OCP Practice Question 2751

Question

Given:

1. public class Main {  
2.   int state = 0;  
3.   Main(int s) { state = s; }  
4.   public static void main(String... hi) {  
5.     Main b1 = new Main(1);  
6.     Main b2 = new Main(2);  
7.     System.out.println(b1.go(b1) + " " + b2.go(b2));  
8.   }  /*w  w w .  ja  va  2 s.  c  o  m*/
9.   int go(Main b) {  
10.     if(this.state == 2) {  
11.       b.state = 5;  
12.       go(this);  
13.     }  
14.     return ++this.state;  
15.  } 
16.} 

What is the result?

  • A. 1 2
  • B. 1 3
  • C. 1 6
  • D. 1 7
  • E. 2 6
  • F. 2 7
  • G. Compilation fails.
  • H. An exception is thrown at runtime.


F   is correct.

Note

There are only two Main objects.

The first call to go() is pretty straightforward, but don't get confused; "b" and "this" are referring to the same object.

The second call to go() is a little trickier-the "if" test is true, so go() is invoked a third time.

The result of the third invocation would be 6, but it's not kept.

When control is returned to the second invocation of go(), state (from the same object) is incremented again, to 7.




PreviousNext

Related