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;
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
, orint
:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With