明天我要进行考试,但我听不懂书中的解释,感谢您的帮助:
public class TestClass{
public static void main(String[] args) throws Exception{
int a = Integer.MIN_VALUE;
int b = -a;
System.out.println( a+ " "+b);
}
}
输出:
-2147483648 -2147483648
为什么要打印2个相同大小的负数而不是正负数?
最佳答案
由于无声整数溢出:Integer.MIN_VALUE
是-2^31
,Integer.MAX_VALUE
是2^31-1
,因此-Integer.MIN_VALUE
是2^31
,即Integer.MAX_VALUE + 1
,根据定义,该值对于整数而言太大。因此它溢出并变成Integer.MIN_VALUE
...
您还可以检查以下内容:
System.out.println(Integer.MAX_VALUE + 1);
打印相同的东西。
从技术上讲,结果由Java Language Specification #15.18.2定义: