Strange division behavior of -ve int / -ve int, in java
Although I'm not new to java, I observed this peculiar behavior the other day. I was updating my basics by running code that consisted of basic arithmetic operations. Now according to java (and basic rules of arithmetic), -ve * -ve
OR -ve / -ve
is a number +ve
.
But compiling this source: -
int b = Integer.MIN_VALUE / -1;
System.out.println("b: " + b);
Gives me the output: -
b: -2147483648
What is -ve
, can someone point me to what happened? I know this is a small thing that I cannot know about.
source to share
Divide by -1
the same as negating a number.
Since the range of integers (-2147483648 to 2147483647) is 1 the largest on the negative side -Integer.MIN_VALUE
is equal Integer.MAX_VALUE+1
, which overflows to Integer.MIN_VALUE
.
System.out.println(Integer.MIN_VALUE == -Integer.MIN_VALUE); // prints 'true'
source to share