Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?

System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);

is true.

I understand that integer in Java is 32 bit and can't go above 231-1, but I can't understand why adding 1 to its MAX_VALUE results in MIN_VALUE and not in some kind of exception. Not mentioning something like transparent conversion to a bigger type, like Ruby does.

Is this behavior specified somewhere? Can I rely on it?

like image 573
Oleg Mikheev Avatar asked Feb 22 '12 15:02

Oleg Mikheev


People also ask

What is integer Min_value and integer MAX_VALUE?

MIN_VALUE. The Integer. MIN_VALUE is a constant in the Integer class that represents the minimum or least integer value that can be represented in 32 bits, which is -2147483648, -231. This is the lowest value that any integer variable in Java can hold.

What is integer MAX_VALUE +1?

Integer. MAX_VALUE represents the maximum positive integer value that can be represented in 32 bits (i.e., 2147483647 ). This means that no number of type Integer that is greater than 2147483647 can exist in Java.

Why is there no positive equivalent for integer Min_value?

Each negative number other than Integer. MIN_VALUE corresponds to a positive number that is both its negation and its absolute value. Integer. MIN_VALUE is left over, with no corresponding positive int.

What happens when you do max integer Max integer?

As int data type is 32 bit in Java, any value that surpasses 32 bits gets rolled over. In numerical terms, it means that after incrementing 1 on Integer. MAX_VALUE (2147483647), the returned value will be -2147483648. In fact you don't need to remember these values and the constants Integer.


1 Answers

Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE. Relevant JLS

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

like image 140
Bozho Avatar answered Sep 20 '22 10:09

Bozho