why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?

后端 未结 8 1900
鱼传尺愫
鱼传尺愫 2020-11-27 06:57

System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);

is true.

I understand that integer in Java is 32 bit and can\'t go above 23

8条回答
  •  情书的邮戳
    2020-11-27 07:17

    The integer storage gets overflowed and that is not indicated in any way, as stated in JSL 3rd Ed.:

    The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a NullPointerException if unboxing conversion (§5.1.8) of a null reference is required. Other than that, the only integer operators that can throw an exception (§11) are the integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3), which throw an ArithmeticException if the right-hand operand is zero, and the increment and decrement operators ++(§15.15.1, §15.15.2) and --(§15.14.3, §15.14.2), which can throw an OutOfMemoryError if boxing conversion (§5.1.7) is required and there is not sufficient memory available to perform the conversion.

    Example in a 4-bits storage:

    MAX_INT: 0111 (7)
    MIN_INT: 1000 (-8)
    

    MAX_INT + 1:

     0111+
     0001
     ----
     1000
    

提交回复
热议问题