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?
When you negate
-2147483648
, it resolves to2147483648
, which exceeds theInteger.MAX_VALUE
with1
. Then the value overflows toInteger.MIN_VALUE
again.From the JLS:
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 leading0
and 311
bits. Adding1
would make it a number with a leading1
and 31 trailing0
s, which is actually the two's complement representation ofInteger.MIN_VALUE
.Java uses two's complement representation of signed numbers. Therefore, the change of sign operation, consists of two steps:
1
to the result.2147483648
's representation is shown below:Inverting it produces
Adding
1
makes it the same number again, i.e.due to integer overflow.