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








Question

What change would allow the following code snippet to compile? (Choose all that apply)

     long x = 1;     // line 3
     int  y = 2 * x; // line 4 
  1. No change; it compiles as is.
  2. Change the data type of x on line 3 to short.
  3. Cast x on line 4 to int.
  4. Cast 2 * x on line 4 to int.
  5. Change the data type of y on line 4 to short.
  6. Change the data type of y on line 4 to long.




Answer



B, C, D, F.

Note

A is not correct.

The code will not compile as is since the 2 * x promotes to long. The value 2 * x is promoted to long and cannot be automatically stored in y, which is in an int value.

B, C, and D changed the long value to int.

E is wrong since it makes the value in a smaller data type.

F solves the problem by increasing the data type to long, which is allowed.