Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the negative of Integer.MIN_VALUE give the same value? [duplicate]

Consider the below java code.

Integer value = Integer.MIN_VALUE;
System.out.println(value);

value = -value;
System.out.println(value);

Output

-2147483648
-2147483648

How the negative value of Integer.MIN_VALUE value results the same value?

However the result can't be 2147483648 because the maximum value of Integer in java is 2147483647.

But want to know why -2147483648? What kind of bit-wise operations are happening internally?

like image 445
Nageswaran Avatar asked Jul 21 '15 13:07

Nageswaran


1 Answers

When you negate -2147483648, it resolves to 2147483648, which exceeds the Integer.MAX_VALUE with 1. Then the value overflows to Integer.MIN_VALUE again.

From the JLS:

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.

So, every unary operation done on an integer will actually be applied on the two's complement representation of the number. When the Integer.MAX_VALUE is reached it will consist of a leading 0 and 31 1 bits. Adding 1 would make it a number with a leading 1 and 31 trailing 0s, which is actually the two's complement representation of Integer.MIN_VALUE.

like image 88
Konstantin Yovkov Avatar answered Oct 24 '22 06:10

Konstantin Yovkov