Test with Division by Zero
In the previous step, we saw how Double.isInfinite()
works with predefined infinity values. Now, let's explore a common scenario where infinity can arise in calculations: division by zero.
In standard arithmetic, division by zero is undefined. However, in floating-point arithmetic (which double
uses), dividing a non-zero number by zero results in positive or negative infinity, depending on the sign of the numerator. Dividing zero by zero, or infinity by infinity, results in a special value called "Not a Number" (NaN), which we will cover in the next step.
Let's modify our program to demonstrate division by zero and check the result using Double.isInfinite()
.
-
Open the HelloJava.java
file in the WebIDE editor. You should be in the ~/project
directory.
-
Replace the current code with the following:
public class HelloJava {
public static void main(String[] args) {
double positiveResult = 10.0 / 0.0;
double negativeResult = -10.0 / 0.0;
double zeroResult = 0.0 / 10.0;
System.out.println("Result of 10.0 / 0.0: " + positiveResult);
System.out.println("Is 10.0 / 0.0 infinite? " + Double.isInfinite(positiveResult));
System.out.println("Result of -10.0 / 0.0: " + negativeResult);
System.out.println("Is -10.0 / 0.0 infinite? " + Double.isInfinite(negativeResult));
System.out.println("Result of 0.0 / 10.0: " + zeroResult);
System.out.println("Is 0.0 / 10.0 infinite? " + Double.isInfinite(zeroResult));
}
}
Here's what's happening in this new code:
double positiveResult = 10.0 / 0.0;
: We divide a positive number (10.0
) by zero (0.0
). In floating-point arithmetic, this results in positive infinity.
double negativeResult = -10.0 / 0.0;
: We divide a negative number (-10.0
) by zero (0.0
). This results in negative infinity.
double zeroResult = 0.0 / 10.0;
: We divide zero (0.0
) by a non-zero number (10.0
). This results in zero, which is a finite number.
- We then print the results of these divisions and use
Double.isInfinite()
to check if each result is infinite.
-
Save the file (Ctrl+S or Cmd+S).
-
Compile the modified program in the Terminal:
javac HelloJava.java
Again, no output indicates successful compilation.
-
Run the program:
java HelloJava
You should see output similar to this:
Result of 10.0 / 0.0: Infinity
Is 10.0 / 0.0 infinite? true
Result of -10.0 / 0.0: -Infinity
Is -10.0 / 0.0 infinite? true
Result of 0.0 / 10.0: 0.0
Is 0.0 / 10.0 infinite? false
This demonstrates that dividing a non-zero floating-point number by zero correctly produces infinity (positive or negative), and Double.isInfinite()
accurately identifies these results. Dividing zero by a non-zero number results in zero, which is not infinite.