为什么Java中Integer.MIN_VALUE等于负Integer.MIN_VALUE

190 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

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

  1. 当-2147483648转为正数时:Math.abs(-2147483648) == 2147483648。
  2. 当2147483648赋值给int时,int正数只能表示2147483647,也就是说:abs Integer.MIN_VALUE = Integer.MAX_VALUE + 1。
  3. 综上,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不保证结果非负数?

看源码: ![在这里插入图片描述](img-blog.csdnimg.cn/16561427ebf… =x80) 原来abs用到了减号转换,也就是上述所说的int最小负数转正数溢出问题。