You know that byte b= x;
is equivalent to byte b= 24;
, and an intelligent compiler can also tell that, but Java is specified in a very precise way to ensure that all compilers do the same thing, and it does not allow compilers to notice this equivalence for purposes of accepting or rejecting the program. (They can use it for performing optimization afterward, though.) All the compiler is supposed to know is that the expression x
has the static type int
, so it can't guarantee that byte b= x
is assigning a value in the range of byte
.
Instead, you have to write byte b = (byte) x
, explicitly converting ("casting") the expression x
to type byte
.
(This is a general principle with static typing — with any type system, there will always be some otherwise-correct programs that the type system rejects. In this case, the type system doesn't let you assign from int
to byte
without a cast.)