2
votes

According to https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html a byte in Java is:

"The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). "

If I write the maximum value (127) in two's complement form in Java I am able to save it in a byte type.

byte positive127 = 0b01111111;

However, if I try to do the same for the minimum value -128 it is interpreted as an integer. I am not able to save it in a byte.

byte negative127 = 0b10000000;

Picture from IDE

Can someone explain to me why this is not possible when the documentation states that the byte type should be able to hold this value?

Thanks in advance!

1

1 Answers

6
votes

0b10000000 is the positive int 128. There are no literal representations directly for byte, only int, long, float, double, char, boolean, String and for null. You will need a cast to assign it to a byte.

byte negative128 = (byte)0b10000000;

This is the same as any other representation:

byte a = (byte)128;
byte b = (byte)0x80;

If the conversion from an int compile-time constant expression (such as a literal) to byte does not involve a truncation (i.e. -128 to 127 inclusive) then the language allows the cast to be elided.

byte c = -128;