Integer.MIN_VALUE == -Integer.MIN_VALUE
public static void main(String[] args) {
int i = Integer.MIN_VALUE;
System.out.println(Integer.toBinaryString(i)); // 10000000000000000000000000000000
System.out.println(Integer.toBinaryString(-i)); // 10000000000000000000000000000000
while (i != 0 && i == -i) {
// 死循环,因为 i == -i 成立
}
// 注:
System.out.println(Integer.toBinaryString(Integer.MAX_VALUE)); // 01111111111111111111111111111111
System.out.println(Integer.toBinaryString(Integer.MAX_VALUE + 1));// 10000000000000000000000000000000
}
为什么Integer.MIN_VALUE == -Integer.MIN_VALUE?
int的表示范围:-2147483648~2147483647
- 当-2147483648转为正数时:Math.abs(-2147483648) == 2147483648。
- 当2147483648赋值给int时,int正数只能表示2147483647,也就是说:abs Integer.MIN_VALUE = Integer.MAX_VALUE + 1。
- 综上,int表示2147483648会溢出,变成01111111111111111111111111111111(2147483647)+ 1 = 10000000000000000000000000000000(-2147483648),也就刚好是Integer.MIN_VALUE。
还会产生其它问题
System.out.println(Math.abs(Integer.MIN_VALUE)); // -2147483648
竟然返回了负数,也就是说 Math.abs 对Integer.MIN_VALUE无效,且abs不保证一定返回非负结果。
为什么abs不保证结果非负数?
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/180275.html