Java OCA OCP Practice Question 445

Question

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

int time = 11; 
int day = 4; 
String dinner = time > 10 ? day ? "Takeout" : "Salad" : "Leftovers"; 
  • A. Takeout
  • B. Salad
  • C. The code does not compile but would compile if parentheses were added.
  • D. None of the above


D.

Note

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

The code does not compile because day is an int, not a boolean expression, in the second ternary operation, making Option D the correct answer.

Remember that in Java, numeric values are not accepted in place of boolean expressions in if-then statements or ternary operations.




PreviousNext

Related