9
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

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
rajeev
  • 499
  • 1
  • 8
  • 17
  • overflow max value is 127 – nachokk Sep 12 '13 at 02:13
  • This question is slightly similar to [this question](http://stackoverflow.com/questions/8121947/is-there-an-explanation-for-the-behavior-of-this-java-bytebuffer). – Mark Sep 12 '13 at 02:18
  • [Sign extension](http://en.wikipedia.org/wiki/Sign_extension), plus `Byte.MAX_VALUE` is 127. – Ted Hopp Sep 12 '13 at 02:21

2 Answers2

12

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • For further explanation, the leading bit will become the sign of your integer value. – Mark Sep 12 '13 at 02:17
0

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.

Mark
  • 8,046
  • 15
  • 48
  • 78
  • There is nothing wrong with byte as you have stated. The user should know what is range of input and as per that appropriate placeholder should be selected. – Abhishek Jul 07 '20 at 10:34