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