Dividing an integer by zero is invalid and throws ArithmeticException , but dividing a floating-point value by zero does not cause an exception. Floating-point arithmetic can overflow to infinity if the result of the operation is too large for a double or a float , or underflow to zero if the result is too small for a double or a float . Java provides the special floating-point values POSITIVE_INFINITY , NEGATIVE_INFINITY , and NaN (Not a Number) to denote these results. These values are defined as special constants in the Float class and the Double class.
If a positive floating-point number is divided by zero, the result is POSITIVE_INFINITY . If a negative floating-point number is divided by zero, the result is NEGATIVE_INFINITY . If a floating-point zero is divided by zero, the result is NaN , which means that the result is undefined mathematically. The string representation of these three values are Infinity, -Infinity, and NaN. For example,
System.out.print(1.0 / 0); // Print Infinity System.out.print(1.0 / 0); // Print Infinity System.out.print(0.0 / 0); // Print NaN
These special values can also be used as operands in computations . For example, a number divided by POSITIVE_INFINITY yields a positive zero. Table E.1 summarizes various combinations of the / , * , % , + , and “ operators.
x | y | x/y | x*y | x%y | x + y | x “ y |
---|---|---|---|---|---|---|
Finite | ± 0.0 | ± | ± 0.0 | NaN | Finite | Finite |
Finite | ± | ± 0.0 | ± 0.0 | x | ± | |
± 0.0 | ± 0.0 | NaN | ± 0.0 | NaN | ± 0.0 | ± 0.0 |
± | Finite | ± | ± 0.0 | NaN | ± | ± |
± | ± | NaN | ± 0.0 | NaN | ± | |
± 0.0 | ± | ± 0.0 | NaN | ± 0.0 | ± | ± 0.0 |
NaN | Any | NaN | NaN | NaN | NaN | NaN |
Any | NaN | NaN | NaN | NaN | NaN | NaN |
Note
If one of the operands is NaN, the result is NaN. |