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.
If you look at the actual memory used to store
-1in signed byte, then you will see that it is0xff. However, in the language itself, rather than the binary representation,0xffis simply out of range for a byte. The binary representation of-1will 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
0xffffffffis anintliteral 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.