Java OCA OCP Practice Question 584

Question

What is the output of the following code?

3: byte a = 40, b = 50; 
4: byte sum = (byte) a + b; 
5: System.out.println(sum); 
  • A. 40
  • B. 50
  • C. 90
  • D. The code will not compile because of line 4.
  • E. An undefined value.


D.

Note

Line 4 generates a possible loss of precision compiler error.

The cast operator has the highest precedence, so it is evaluated first, casting a to a byte.

The addition is evaluated, causing both a and b to be promoted to int values.

The value 90 is an int and cannot be assigned to the byte sum without an explicit cast, so the code does not compile.

The code could be corrected with parentheses around (a + b), in which case option C would be the correct answer.




PreviousNext

Related