Java OCA OCP Practice Question 1746

Question

What is the result of compiling and running the following program?.

public class Main {
  public static void main(String[] args) {
    byte b = 128;
    int  i = b;
    System.out.println(i);
  }
}

Select the one correct answer.

  • (a) The program will not compile because a byte value cannot be assigned to an int variable without using a cast.
  • (b) The program will compile and print 128, when run.
  • (c) The program will not compile because the value 128 is not in the range of values for the byte type.
  • (d) The program will compile but will throw a ClassCastException when run.
  • (e) The program will compile and print 255, when run.


(c)

Note

Variables of the type byte can store values in the range -128 to 127.

The expression on the right-hand side of the first assignment is the int literal 128.

Had this literal been in the range of the byte type, an implicit narrowing conversion would have been applied to convert it to a byte value during assignment.

Since 128 is outside the range of the type byte, the program will not compile.




PreviousNext

Related