-2

https://www.ideone.com/gYreaO , why does this really happen? Why does it take the two's complement way to display the value?

byte a=123;
byte b=5;
byte c=(byte)(a+b);
System.out.println(c);
azro
  • 53,056
  • 7
  • 34
  • 70
Karma
  • 9
  • 1
  • Maximum value for `byte` is 127, so if you add one, it starts at the other side of the spectrum, which is the minimum value of `byte`, which is -128. – MWB Nov 04 '18 at 17:32
  • 1
    Because the valid range of a `byte` is `-128` to `127`. Not `128`. `System.out.println((byte) 128);` – Elliott Frisch Nov 04 '18 at 17:33
  • When you'll take a look at the answer, think about vote up/accept one ;) – azro Nov 05 '18 at 03:33

3 Answers3

2

A byte which is 8bit can holds 2^8 = 256 values, first 7b for value, 1b for sign, all in the 2-complement way :

-128, -127, ... 0, 1, 2 ..., 126, 127

When you are as 127, and you do +1, it goes back the first value of the range because of the bonary operation

01111110  126
01111111  127
10000000 -128
10000001 -127

Code demo


Exactly the same happens, with int when you reach Integer.MAX_VALUE

System.out.println(Integer.MAX_VALUE + 1);                      // -2147483648
System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE); // true
azro
  • 53,056
  • 7
  • 34
  • 70
1

The byte range is -128 to 127. Here is what happens when you add one to max range of byte:

  0 1 1 1  1 1 1 1  -->   127
+ 0 0 0 0  0 0 0 1  -->     1
------------------
  1 0 0 0  0 0 0 0  -->  -128

Please note that leftmost bit is the sign bit and since the sign bit is set, you can get the value of the variable by two's complement.

S.K.
  • 3,597
  • 2
  • 16
  • 31
1

The byte data type has min value -128(=-2^7) and max value 127(=2^7-1).
The addition (a+b) produces the result:
128 (binary 10000000 for the int data type) because it is converted to int,
but the casting (byte)(a+b) squeezes it back to 1 byte and you get
-128(binary 10000000 for the byte data type).

forpas
  • 160,666
  • 10
  • 38
  • 76