問題描述
System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);
是真的.
我知道 Java 中的整數(shù)是 32 位的,不能超過 231-1,但我不明白為什么在其 MAX_VALUE
結(jié)果中加 1在 MIN_VALUE
而不是某種異常.更不用說像 Ruby 那樣將透明轉(zhuǎn)換為更大的類型.
I understand that integer in Java is 32 bit and can't go above 231-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?
推薦答案
因?yàn)檎麛?shù)溢出.當(dāng)它溢出時,下一個值是 Integer.MIN_VALUE
.相關(guān)JLS
Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE
. Relevant JLS
如果整數(shù)加法溢出,則結(jié)果是數(shù)學(xué)和的低位,以某種足夠大的二進(jìn)制補(bǔ)碼格式表示.如果發(fā)生溢出,則結(jié)果的符號與兩個操作數(shù)值的數(shù)學(xué)和的符號不同.
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.
這篇關(guān)于為什么 Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!