Given that byte,short and int are signed, why do byte and short in Java not get the usual signed two's complement treatment ? For instance 0xff is illegal for byte.
This has been discussed before here but I couldn't find a reason for why this is the case.
You can write
but you can't write
as the 0xFF is an
int
value not abyte
so its equal to 255. There is no way to define a byte or short literal, so you have to cast it.BTW You can do
even
You can literally set a byte, but surprisingly, you have to use more digits:
The logic is, that 0xff is implicitly 0x000000ff, which exceeds the range of a byte. (255)
It's not the first idea you get, but it has some logic. The longer number is a smaller number (and smaller absolute value).
it is legal, but you need to cast it to byte explicitly, i.e. (byte)0xff because it is out of range.
If you look at the actual memory used to store
-1
in signed byte, then you will see that it is0xff
. However, in the language itself, rather than the binary representation,0xff
is simply out of range for a byte. The binary representation of-1
will indeed use two's complement but you are shielded from that implementation detail.The language designers simply took the stance that trying to store 255 in a data type that can only hold -128 to 127 should be considered an error.
You ask in comments why Java allows:
The literal
0xffffffff
is anint
literal and is interpreted using two's complement. The reason that you cannot do anything similar for a byte is that the language does not provide syntax for specifying that a literal is of typebyte
, or indeedshort
.I don't know why the decision not to offer more literal types was made. I expect it was made for reasons of simplicity. One of the goals of the language was to avoid unnecessary complexity.
The possible values for a
byte
range from -128 to 127.It would be possible to let values outside the range be assigned to the variable, and silently throw away the overflow, but that would rather be confusing than conventient.
Then we would have:
In most situations it's better to have the compiler tell you that the value is outside the range than to "fix" it like that.