What happens when I assign value larger than byte?

According to official oracle documentation, Byte is

  • Byte: 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). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation

My code is

public class B

    public static void main(String args[])
        byte b;




What happens when I assign value larger than byte. Java compiler will report an error. I will go if I cast this value to byte

byte b = (byte) 128;

I do not understand the output of this program?

3 Answers

Matthew Ivanoff On Best Solutions

For byte type, you only have 8 bits to store the value. You can have only 256 distinct values (2^8 = 256). Java represents negative values with '1' as the highest bit:

-128 (dec) => 10000000 (bit)
-127 (dec) => 10000001 (bit)
-1   (dec) => 11111111 (bit)
0    (dec) => 00000000 (bit)
+1   (dec) => 00000001 (bit)
+127 (dec) => 01111111 (bin)

When you try to set a value that needs more than one byte to store then setting the lowest byte to a byte value happens:

+129 (dec) => 00000000 00000000 00000000 10000001  (int representation)

but 10000001 (bit) is -127 (dec) in byte representation of java type (as described above)

To have a better understanding of the overflow problem in Java, see the article: https://medium.com/@jeanvillete/java-numeric-overflow-underflow-d6b206f96d88

Sachin Maharjan On

Beacause byte datatype is of 1 byte as per name. so, its range is -127 to +126 (i.e capacity is 256). Hence +129 cannot be stored in byte datatype. so +129 is truncated to -127.

Carlos Heuberger On

129 is an integer literal and, since not followed by L or l, it is of type int. This has 32 bits (4 bytes):

0000 0000  0000 0000  0000 0000  1000 0001

When cast to byte 5.1.3. Narrowing Primitive Conversion is done which discard all but the lower 8 bits so the values fits into byte.

In your example we will end with just the lower 8 bits

1000 0001

since Java uses two's complement to represent byte, this number is considered negative since the highest bit is set.

If the value was 257, its binary representation would be:

0000 0000  0000 0000  0000 0001  0000 0001

converted to byte as:

0000 0001

or just +1 (highest bit not set).