OCA Java SE 8 Operators/Statements - OCA Mock Question Operator and Statement 14








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); 
     
  1. 40
  2. 50
  3. 90
  4. The code will not compile because of line 4.
  5. An undefined value.




Answer



D.

Note

Line 4 generates a possible loss of precision compiler error.

It only casts one operand, the following code changes the casting to cast the result of the addition.

public class Main{
   public static void main(String[] argv){
        byte a = 40, b = 50; 
        byte sum = (byte) (a + b); 
        System.out.println(sum); 
   }
}