How to Check If a Number Is Infinite in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a double value in Java represents positive or negative infinity. This is a crucial skill when dealing with floating-point calculations that might produce results outside the standard numerical range, such as those involving division by zero.

Through hands-on exercises, you will utilize the Double.isInfinite() method to identify infinite values, explore how division by zero can lead to infinity, and understand the distinction between infinite values and NaN (Not-a-Number).


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/operators("Operators") java/SystemandDataProcessingGroup -.-> java/math_methods("Math Methods") java/SystemandDataProcessingGroup -.-> java/system_methods("System Methods") subgraph Lab Skills java/data_types -.-> lab-559964{{"How to Check If a Number Is Infinite in Java"}} java/operators -.-> lab-559964{{"How to Check If a Number Is Infinite in Java"}} java/math_methods -.-> lab-559964{{"How to Check If a Number Is Infinite in Java"}} java/system_methods -.-> lab-559964{{"How to Check If a Number Is Infinite in Java"}} end

Use Double.isInfinite() for Check

In this step, we will learn how to check if a double value in Java represents positive or negative infinity. This is particularly useful when dealing with calculations that might result in values outside the normal range of floating-point numbers, such as division by zero.

Java provides a built-in method called isInfinite() in the Double class specifically for this purpose.

Let's create a simple Java program to demonstrate how to use Double.isInfinite().

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open. You should be in the ~/project directory.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            double positiveInfinity = Double.POSITIVE_INFINITY;
            double negativeInfinity = Double.NEGATIVE_INFINITY;
            double finiteNumber = 10.0;
    
            System.out.println("Is positiveInfinity infinite? " + Double.isInfinite(positiveInfinity));
            System.out.println("Is negativeInfinity infinite? " + Double.isInfinite(negativeInfinity));
            System.out.println("Is finiteNumber infinite? " + Double.isInfinite(finiteNumber));
        }
    }

    Let's look at the new parts of this code:

    • double positiveInfinity = Double.POSITIVE_INFINITY;: This line declares a double variable and assigns it the special value representing positive infinity.
    • double negativeInfinity = Double.NEGATIVE_INFINITY;: This line declares a double variable and assigns it the special value representing negative infinity.
    • double finiteNumber = 10.0;: This declares a regular double variable with a finite value.
    • System.out.println("Is positiveInfinity infinite? " + Double.isInfinite(positiveInfinity));: This line calls the Double.isInfinite() method with positiveInfinity as the argument. The method returns true if the value is infinite (either positive or negative) and false otherwise. The result is then printed to the console.
    • The next two System.out.println lines do the same for negativeInfinity and finiteNumber.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Run the following command:

    javac HelloJava.java

    If the compilation is successful, you will not see any output.

  5. Finally, run the compiled program using the java command:

    java HelloJava

    You should see output similar to this:

    Is positiveInfinity infinite? true
    Is negativeInfinity infinite? true
    Is finiteNumber infinite? false

This output confirms that Double.isInfinite() correctly identifies both positive and negative infinity, while returning false for a regular finite number.

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().

  1. Open the HelloJava.java file in the WebIDE editor. You should be in the ~/project directory.

  2. 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.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java

    Again, no output indicates successful compilation.

  5. 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.

Differentiate Infinite from NaN

In the previous steps, we learned about Double.isInfinite() and how division by zero can result in infinity. However, there's another special value in floating-point arithmetic called NaN, which stands for "Not a Number". NaN represents the result of an undefined or unrepresentable operation, such as dividing zero by zero or taking the square root of a negative number.

It's important to be able to differentiate between infinite values and NaN, as they represent different types of exceptional results. Java provides the Double.isNaN() method to check if a double value is NaN.

Let's modify our program one last time to include a calculation that results in NaN and see how to distinguish it from infinity.

  1. Open the HelloJava.java file in the WebIDE editor. You should be in the ~/project directory.

  2. Replace the current code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            double positiveInfinity = 10.0 / 0.0;
            double nanResult = 0.0 / 0.0;
            double finiteNumber = 5.0;
    
            System.out.println("Result of 10.0 / 0.0: " + positiveInfinity);
            System.out.println("Is 10.0 / 0.0 infinite? " + Double.isInfinite(positiveInfinity));
            System.out.println("Is 10.0 / 0.0 NaN? " + Double.isNaN(positiveInfinity));
    
            System.out.println("Result of 0.0 / 0.0: " + nanResult);
            System.out.println("Is 0.0 / 0.0 infinite? " + Double.isInfinite(nanResult));
            System.out.println("Is 0.0 / 0.0 NaN? " + Double.isNaN(nanResult));
    
            System.out.println("Result of 5.0: " + finiteNumber);
            System.out.println("Is 5.0 infinite? " + Double.isInfinite(finiteNumber));
            System.out.println("Is 5.0 NaN? " + Double.isNaN(finiteNumber));
        }
    }

    Here's a breakdown of the changes:

    • double positiveInfinity = 10.0 / 0.0;: We keep the division that results in positive infinity.
    • double nanResult = 0.0 / 0.0;: This line performs division of zero by zero, which results in NaN.
    • double finiteNumber = 5.0;: A regular finite number for comparison.
    • We now include calls to Double.isNaN() for each result, in addition to Double.isInfinite().
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. 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
    Is 10.0 / 0.0 NaN? false
    Result of 0.0 / 0.0: NaN
    Is 0.0 / 0.0 infinite? false
    Is 0.0 / 0.0 NaN? true
    Result of 5.0: 5.0
    Is 5.0 infinite? false
    Is 5.0 NaN? false

This output clearly shows the difference between infinite values and NaN. Double.isInfinite() returns true only for positive or negative infinity, while Double.isNaN() returns true only for NaN. For a finite number, both methods return false. Understanding this distinction is crucial for handling potential errors and unexpected results in floating-point calculations.

Summary

In this lab, we learned how to check if a double value in Java represents positive or negative infinity using the Double.isInfinite() method. We saw how to use this method with predefined Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY values, as well as with a finite number, to understand its behavior. This method is crucial for handling potential infinite results from floating-point calculations.