Special Values: Infinity, -Infinity, and NaN
You'll learn how Java's floating-point types handle extreme results like dividing by zero or taking the square root of a negative number.
The Concept
In everyday math, dividing by zero is undefined. But Java's float and double types don't crash your program when unusual operations occur—they return special values instead.
Java defines three important special values:
- Infinity: Represents a positive value too large to express (like
1.0 / 0.0) - -Infinity: Represents a negative value too large to express (like
-1.0 / 0.0) - NaN (Not-a-Number): Represents an undefined or unrepresentable result (like
0.0 / 0.0)
Think of these like warning signs on a road: instead of blocking you entirely, they signal that something mathematically strange happened, and your program continues running.
How They Arise
double positiveInfinity = 1.0 / 0.0; // Infinity
double negativeInfinity = -1.0 / 0.0; // -Infinity
double notANumber = 0.0 / 0.0; // NaN
float alsoInfinity = 1.0f / 0.0f; // Infinity (works with float too)
Once you have these special values, they propagate through calculations:
double result1 = positiveInfinity + 100.0; // Still Infinity
double result2 = notANumber + 5.0; // Still NaN
Important quirk: NaN is not equal to anything, including itself! NaN == NaN is false.
Why This Matters
Instead of crashing, Java lets your program detect and handle mathematical edge cases gracefully. You'll later learn to check for these values explicitly.
Key Takeaway: Java's floating-point types use Infinity, -Infinity, and NaN to represent results from extreme operations like division by zero, allowing programs to continue running rather than crashing.