Why is number divided by zero infinity in Java?

后端 未结 5 1313
遥遥无期
遥遥无期 2020-12-04 00:00

Why should the following code in Java

System.out.println(new Integer(1)/ new Double(0));

print \'Infinity\' and not undefined. Isn\'t that

5条回答
  •  青春惊慌失措
    2020-12-04 01:01

    No, you can't divide by zero in math, but in Java Infinity is correct for new Integer(1)/ new Double(0). new Integer(0)/ new Double(0) would be undefined (NaN).

    Java follows IEEE standards, so for floating point operations such as this, Infinity is correct. Had it been 1/0, an ArithmeticException would have occurred, because in integer division, division by zero is not allowed; there is no int representation for infinity.

    Specifically, in the JLS, Section 15.17.2:

    [I]f the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

    And

    The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:

    Division of a zero by a zero results in NaN Division of a nonzero finite value by a zero results in a signed infinity.

提交回复
热议问题