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.

+3


source to share


2 answers


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'

      

+10


source


You have an overflow. According to the java spec, the sign is not guaranteed on overflow.

Overflow occurs due to the fact that



Integer.MIN_VALUE = -2147483648;
Integer.MAX_VALUE = 2147483647;

      

so -2147483648 * (- 1) - 2147483648, which exceeds the maximum value.

+2


source







All Articles