本文介绍了为什么Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);
is是的。
我知道Java中的整数是32位且不能超过2 ^ 31-1,但我无法理解为什么在MAX_VALUE中加1导致MIN_VALUE,而不是某种异常。没有提到类似透明转换为更大类型的东西,比如Ruby。
I understand that integer in Java is 32 bit and can't go above 2^31-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?
推荐答案
因为整数溢出。当它溢出时,下一个值是 Integer.MIN_VALUE
。
Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE
. Relevant JLS
这篇关于为什么Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!