Java arithmetic

why does this code return the wrong value?

int i=Integer.MAX_VALUE+1; long l=Integer.MAX_VALUE+1; System.out.println(l); System.out.println(i); 
+3
source share
4 answers

When you add 1 to Integer.MAX_VALUE , it overflows and wraps up to Integer.MIN_VALUE .

This is because Java uses two additions to represent integers. Example in 4 bits:

 0000 : 0 0001 : 1 ... 0111 : 7 (max value) 1000 : -8 (min value) ... 1110 : -2 1111 : -1 

So, when you add 1 to 0111 (max), it goes into 1000 , and the minimum. Expand this idea to 32 bits and it works the same.


As for why your long also shows the wrong result, this is because it performs the addition on int , and then implicitly converts to long . You need to do:

 long l = (long) Integer.MAX_VALUE + 1 System.out.println(l); // now prints the correct value 
+9
source

As the name Integer.MAX_VALUE , the maximum value is available for Integer . In java, when an integer goes to the maximum value by 1 (or overflows by 1), then its value will be Integer.MIN_VALUE .

If the integer addition overflows, then the result is the least significant bits of the mathematical sum, presented in some fairly large format with two additions. If overflow occurs, the sign of the result does not coincide with the sign of the mathematical sum of the two values โ€‹โ€‹of the operand.

Beware that with Float or Double you will not have this overflow, the value will be POSITIVE_INFINITY

An operation that overflows creates a signed infinity, an operation that has a lower value creates a denormalized value or an equal sign, and an operation that does not have a mathematically defined result produces NaN.


Resources:

+3
source

Here you overflow the 32-bit integer type, trying to save a value that cannot be represented by this type (2 ^ 31 - 1):

 int i = Integer.MAX_VALUE + 1; 
+2
source

The Java integer is a 32-bit type of a signed type: from -2,147,483,648 to 2,147,483,647.

You cannot set the i integer variable, as in i=Integer.MAX_VALUE+1;

0
source

Source: https://habr.com/ru/post/1397273/


All Articles