How does overflow work in java?

Luisk4 :

I've read about overflow, I know that "Overflow is when a number is so large that it will no longer fit within the data type, so the system “wraps around” to the next lowest value and counts up from there".

For example:

short s = (short)1921222; // Stored as 20678

In that example we started counting from -32768 (Short.MIN_VALUE), but when I try to prove in another integer data types, it doesn't seem work the same way...

byte b = (byte)400; // Stored as -112

The example above started counting from 0 that was the only way I found to get -112

I don't know if I am doing something wrong.

S.L. Barth - Reinstate Monica :

The Java Language Specification says:

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units.

So, short and byte are both two's complement integers.

short is 16 bits, meaning it can hold 2^16 = 65536 different values. After the 65536th value, it overflows.
1921222 modulo 65536 is 20678 . This is less than 32768 (2^15, the turning point for the two's complement) so we keep a positive number.

byte is 8 bits, meaning it can hold 2^8 = 256 different values. This one overflows after the 256hth value. 400 modulo 256 is 144. This value is higher than 128, the turning point for the two's complement - hence it will be interpreted as a negative two's complement number.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=426847&siteId=1