Java OCA OCP Practice Question 573

Question

What results from attempting to compile and run the following code?

1. public class Conditional { 
2.   public static void main(String args[]) { 
3.     int x = 4; 
4.     System.out.println("value is " + 
5.       ((x > 4) ? 99.99 : 9)); 
6.   } 
7. } 
  • A. The output: value is 99.99
  • B. The output: value is 9
  • C. The output: value is 9.0
  • D. A compiler error at line 5


C.

Note

The optional result values for the conditional operator, 99.99 (a double) and 9 (an int), are of different types.

The result type of a conditional operator must be fully determined at compile time.

In this code the type chosen, using the rules of promotion for binary operands, is double.

Because the result is a double, the output value is printed in a floating-point format.

If the two possible argument types had been entirely incompatible-for example, (x > 4) ? "Hello" : 9-then the compiler would have issued an error at that line.




PreviousNext

Related