In Java, (Number/0) throws an ArithmeticException while (Number/0.0) = Infinity. Why does this happen?

Was it helpful?


Because IEEE-754 floating point numbers have a representation for infinity, whereas integers don't.

In other words, every bit pattern in int represents a normal integer; floating point values are rather more complicated with +/- infinity, "not a number" (NaN) values, normalized values, subnormal values etc.


From here

The IEEE floating-point standard, supported by almost all modern processors, specifies that every floating point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (not a number). There are two zeroes, +0 (positive zero) and −0 (negative zero) and this removes any ambiguity when dividing. In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0. The infinity signs change when dividing by −0 instead.

Integer division by zero is usually handled differently from floating point since there is no integer representation for the result. Some processors generate an exception when an attempt is made to divide an integer by zero, although others will simply continue and generate an incorrect result for the division. The result depends on how division is implemented, and can either be zero, or sometimes the largest possible integer.

Also you can check the JLS which says:

15.17.2 Division Operator
On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

The result of a floating-point division is determined by the specification of IEEE arithmetic: If the result is not NaN, the sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow