开发者

java arithmetic

why this code returns wrong value?

int i=Int开发者_高级运维eger.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);


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


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 :

  • JLS - MIN_VALUE & MAX_VALUE
  • Additive Operators (+ and -) for Numeric Types


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;


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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜