1) Why is the following assignment not allowed:
byte b = 0b11111111; // 8 bits or 1 byte
but this assignment is allowed:
int i = 0b11111111111111111111111111111111; //32 bits or 4 bytes
Both types are signed, and I would expect b
and i
were -1.
2) Why doesn't the Integer MIN_VALUE have a sign?
public static final int MIN_VALUE = 0x80000000;
but the Byte MIN_VALUE does have a sign?
public static final byte MIN_VALUE = -128;
All integer literals have type int
(unless suffixed by an L
or l
). Thus, in the first case, you're storing an int
into a byte
. A narrowing conversion like this is not allowed without a cast, except that if the right side is a constant, it's allowed if the value is in range, which is -128
to 127
. 0b11111111
is 255, though, which is not in range.
As for why int i = 0b11111111111111111111111111111111
is allowed: it's pretty much "because the JLS says so". In fact, that specific example appears in JLS 3.10.1. There's a rule that decimal literals of type int
cannot exceed 214743647 (except in the specific case -2147483648
), but there's no rule about binary literals except that they have to fit into 32 bits.
As I mentioned in a comment, the second question is really a question about the style preference of the programmers who wrote the code, and it's impossible to answer.