Based on the fact that a byte
type in java is a signed 8 bit two\'s complement integer, why doesn\'t the second way of declaring a byte work?
b
Actually, as mentioned by Eng Fouad
, 0b10000000 is an integer literal. Integer literals create an int value, the size of which in Java is 32-bit.The byte data type is an 8-bit signed two's complement integer.
So assigning the integer literal to a byte type would not work. To create a conversion between two incompatible types, one must use a cast.
b = (byte)0b10000000; // (This is narrowing conversion)
Also, the signed 2's complement representation of -128
is 110000000. But, the MSB 's 1 can be discarded(represents negative sign bit) and hence 10000000 is acceptable as 2's complement representation of -128.
0b10000000
is an int
literal (= 0b00000000000000000000000010000000
) which equals to +128
. byte
holds 8 bits and cannot represent +128
. However, you can achieve this as follows:
byte notok = (byte) 0b10000000;