views:

87

answers:

4
+3  Q: 

java arithmetic

why this code returns wrong value?

int i=Integer.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);
+1  A: 

You are overflowing the 32 bit integer type here by trying to store a value that cannot be represented by this type (2^31 - 1):

int i = Integer.MAX_VALUE + 1;
Darin Dimitrov
+2  A: 

As the name says Integer.MAX_VALUE is the max value available for an Integer. In java when an Integer goes over its max value by 1 (or overflows by 1) then its value will be Integer.MIN_VALUE.

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.

Beware, with Float or Double you won't have this overflow, the value will be POSITIVE_INFINITY

An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN.


Resources :

Colin Hebert
+8  A: 

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

This happens because Java uses two's complement to represent integers. An 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 to 1000, and that's the minimum. Expand this idea to 32-bits and it works the same way.


As for why your long is also showing an incorrect result, it's because it's performing addition on int s and then implicitly converting to long. You need to do:

long l = (long) Integer.MAX_VALUE + 1
System.out.println(l); // now prints the correct value
NullUserException
Please tell me whether I understood the algorithm parsing this code virtual machine:long l = Integer.MAX_VALUE +1;1. long l - I said virtual machine to allocate 64 bits of memory for this variable.2. Integer.MAX_VALUE +1 - in this line of virtual machine does not know anything about the variable l. Here a simple arithmetic operation, the result of which - an integer overflow.3. in a memory area of 64 bits (l variable) written expression result from 2nd row - 32 bit incorrect value.I see that we have no logical connection between the first and the second step?its true?
A: 

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

You can't set i integer variable as you did in i=Integer.MAX_VALUE+1;

Junior Mayhé
and what happens in this case:long l=Integer.MAX_VALUE+1;now l is 64 bits.