why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?(为什么 Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?)
问题描述
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01