rajeev
rajeev

Reputation: 499

How a positive value becomes negative after casting byte in Java?

public class Test1 {

    public static void main(String[] args) {

        byte b1=40;
        byte b=(byte) 128;

        System.out.println(b1);
        System.out.println(b);
    }
}

the output is

40
-128

the first output is 40 I understood but the second output -128 How it is possible ? is it possible due to it exceeds its range ? if yes how it works after byte casting...help me

Upvotes: 9

Views: 6752

Answers (2)

Mark
Mark

Reputation: 8441

A byte in Java is represented in 8-bit two's complement format. If you have an int that is in the range 128 - 255 and you cast it to a byte, then it will become a byte with a negative value (between -1 and -128).

That being said, you should probably avoid using byte because there are issues with them. You'll notice if you cast the result to byte, since the operators actually return int. You should just stick to int and long in java since they are implemented better.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

When you cast 128 (10000000 in binary) to an eight-bit byte type, the sign bit gets set to 1, so the number becomes interpreted as negative. Java uses Two's Complement representation, so 10000000 is -128 - the smallest negative number representable with 8 bits.

Under this interpretation, 129 becomes -127, 130 becomes -126, and so on, all the way to 255 (11111111 in binary), which becomes -1.

Upvotes: 12

Related Questions