Aman
Aman

Reputation: 45

What happens when I assign value larger than byte?

What happens when I assign value larger than byte?

According to official oracle documentation, Byte is

My code is

public class B
{

    public static void main(String args[])
    {
        byte b;
        b=(byte)129;
        System.out.println("b="+b);

    }
}   

Output:

b=-127

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?

Upvotes: 2

Views: 4364

Answers (3)

Sachin Maharjan
Sachin Maharjan

Reputation: 78

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.

Upvotes: -1

user85421
user85421

Reputation: 29680

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).

Links:

Upvotes: 4

Matthew I.
Matthew I.

Reputation: 1803

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

Upvotes: 5

Related Questions