Why should the following code in Java
System.out.println(new Integer(1)/ new Double(0));
print \'Infinity\' and not undefined. Isn\'t that
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.