Java provides three special values for both floating-point types (float and double): +Infinity, -Infinity and NaN. These values appear in different cases and can be directly assigned to variables of these types. They are employed in mathematical operations to indicate that a result exceeds the upper or lower bounds of representable numbers, such as when dividing a positive number by zero or subtracting a very large number from another.
Infinity
Double.POSITIVE_INFINITYis a constant that is greater than any number.
double posInf = Double.POSITIVE_INFINITY; // +Infinity
double anotherPosInf = +1 / 0.0; // it's +Infinity, not an exception
double posInfAgain = anotherPosInf + 100; // +Infinity again
In Java, when we write an expression with the division by the real zero 0.0, no errors occur. We also can divide a real value by 0.
Double.NEGATIVE_INFINITYis a constant that is less than any number.
double negInf = Double.NEGATIVE_INFINITY; // -Infinity
double negInfAgain = negInf * 100; // The result is -Infinity
double anotherNegInf = -1.002 / 0.0; // It is also -Infinity
There are no errors in this case, either.
In general, the operations sum and product performed on an infinity value and a regular value return infinity with the same sign. For the operations subtract, remainder, and division, the result also depends on the order of operands.
NaN
Double.NaNis a special constant that represents an undetermined value (such as0 / 0). It does not equal any floating-point or integer number.NaNis an acronym for Not a Number.
double nan = Double.NaN; // the NaN constant
double anotherNan = 0.0 / 0.0; // it's the NaN, not an exception
Also, this value occurs after some operations on infinity values.
double nan = Double.NEGATIVE_INFINITY + Double.POSITIVE_INFINITY; // NaN
double nanToo = Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY; // Also NaN
double notANan = Double.POSITIVE_INFINITY + Double.POSITIVE_INFINITY; // it's +Infinity!
Any arithmetic operation with NaN produces NaN as the result. Actually, the results of arithmetic operations do not contradict the common sense.
The float type has the same special values: Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NaN. The results of arithmetic operations are the same as the ones we discussed above.
Conclusion
Understanding the concepts of +Infinity, -Infinity, and NaN in Java for float and double is crucial for handling exceptional cases in mathematical operations. These special values help prevent program crashes and provide a way to gracefully handle situations where results cannot be represented or are undefined. Properly managing these exceptional situations can lead to more robust and reliable Java programs.