3

Although I am not new to java, I observed this peculiar behavior the other day. I was refreshing my basics by running code consisting of basic arithmetic operations. Now according to java (and basic rules of arithmetic's ofcourse) , -ve * -ve OR -ve / -ve is a +ve number.

But compiling this source:-

int b = Integer.MIN_VALUE / -1;
System.out.println("b:  " + b);

Gives me output:-

b: -2147483648

Which is -ve, Can anyone point me whats wrong? I know it must be small thing that I cant notice.

Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28

2 Answers2

10

To divide by -1 is the same as negating the number.

Since the range of integers (-2147483648 to 2147483647) is 1 larger in magnitude on the negative side -Integer.MIN_VALUE equals Integer.MAX_VALUE+1 which overflows back to Integer.MIN_VALUE.

System.out.println(Integer.MIN_VALUE == -Integer.MIN_VALUE); // prints 'true'
aioobe
  • 413,195
  • 112
  • 811
  • 826
2

You have an overflow. Per java specification, the sign is not guaranteed in overflow.

The overflow is due to the fact that

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

so -2147483648*(-1) is 2147483648, which is over the max value.

alonana
  • 171
  • 2
  • 12