Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

like image 829
One Two Three Avatar asked Feb 10 '23 14:02

One Two Three


1 Answers

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.

like image 168
Jon Skeet Avatar answered Feb 12 '23 06:02

Jon Skeet