Java OCA OCP Practice Question 508

Question

Given the following code snippet, what is the value of myField after it is executed?

int characters = 5; 
int story = 3; 
double myField = characters <= 4 ? 3 : story>1 ? 2 : 1; 
  • A. 2.0
  • B. 3.0
  • C. The code does not compile but would compile if parentheses were added.
  • D. None of the above


A.

Note

While parentheses are recommended for ternary operations, especially embedded ones, they are not required, so Option C is incorrect.

The first ternary operation evaluates characters <= 4 as false, so the second ternary operation is executed.

Since story > 1 is true, the final value of myField is 2.0, making Option A the correct answer.




PreviousNext

Related