Java OCA OCP Practice Question 2772

Question

Given this code in a method:

3.     String s = "-";  
4.     boolean b = false;  
5.     int x = 7, y = 8;  
6.     if((x < 8) ^ (b = true))          s += "^";  
7.     if(!(x > 8) | ++y > 5)            s += "|";  
8.     if(++y > 9 && b == true)          s += "AND";  
9.     if(y % 8 > 1 || y / (x - 7) > 1)  s += " MOD";  
10.     System.out.println(s); 

What is the result?

  • A. -
  • B. -| MOD
  • C. -^| MOD
  • D. -|AND MOD
  • E. -^|AND MOD
  • F. Compilation fails.
  • G. An exception is thrown at runtime.


D is correct.

Note

The first if test fails because both comparisons are true ( "b = true" is an assignment, not a test!) and the ^ is XOR-only one condition can be true.

In the second if test, y is incremented because even though the comparison on the left side of the "|" is true, "|" is NOT a short-circuit operator, so the right side will be evaluated.

The third if test is true because y has been incremented twice, and b was set to true in the first if test.

The fourth if test is true because the left-hand side is true, so the short-circuit operator never tests the right-hand side.

If it did, a divide by zero exception would be thrown.




PreviousNext

Related