This surprised me:
char c = 'M';
byte b = -1;
c = b; //incompatible types
Why is this a possibly lossy conversion? A byte is 8 bits and size of a char in Java is always 16 bits, so I would expect this to be promotion.
char
is unsigned (has a range of 0 to 2^16 - 1), so -1
is not within its range.
byte
, on the other hand, is signed, and has a range of -128 to 127. Therefore, even though a b byte
is represented by half the bits of a char
, not all the possible byte
values are also char
values.
BTW, char
is the only unsigned type is Java, so for other integral types (int
,long
) this assignment would work.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments