java arithmetic

[亡魂溺海] 提交于 2019-12-10 20:29:33

问题


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:


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



回答2:


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



回答3:


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;



回答4:


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;



来源:https://stackoverflow.com/questions/3896865/java-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!