type cast rule in java

So known fact: (byte)1 ^ (byte)1 results in an int (per the spec).

Can someone explain to me why the following is possible without explicit cast (from int to byte)? byte myByte = (byte)1 ^ (byte)1

The following, on the other hand, is not allowed:

int i = 0; byte b = i;

Jon Skeet
people
quotationmark

This:

(byte)1 ^ (byte)1

is a constant expression (JLS 15.28), which is known to be in the range of byte. You can therefore implicitly convert it to byte in an assignment context (JLS 5.2):

In addition, if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

If it weren't a constant expression (e.g. if one of those values were a variable instead) then the assignment would fail.

people

See more on this question at Stackoverflow