Java Float isInfinite Method

JavaJavaBeginner
Practice Now

Introduction

The isInfinite() method is a built-in method of the Float class in Java. It is used to check whether a floating-point value is infinite or not. It returns true for an infinite value and false for a finite value.

Define the main method

The main() method is the entry point of the program. In this step, we'll define the main() method.

public static void main(String[] args) {

}

Create a float variable

In this step, we'll create a float variable and assign it a value. The value can be any finite or infinite float number. In this lab, we'll use Float.POSITIVE_INFINITY and Float.NaN values.

float myFloat = Float.POSITIVE_INFINITY;

Use isInfinite() method

In this step, we'll use the isInfinite() method to check whether the float value is infinite or not.

boolean infinity = Float.isInfinite(myFloat);

if(infinity == true){
  System.out.println("Value is infinite");
} else {
  System.out.println("Value is finite");
}

Here, Float.isInfinite(myFloat) will return true if myFloat value is infinite.

Use isNaN() method

In this step, we'll also use the isNaN() method to check whether the float value is not a number (NaN) or not.

boolean nan = Float.isNaN(myFloat);

if(nan == true){
  System.out.println("Value is not a number (NaN)");
} else {
  System.out.println("Value is not NaN");
}

Here, Float.isNaN(myFloat) will return true if myFloat value is NaN.

Save and Compile

Save the FloatingNumbers.java file and open your Terminal or Command Prompt. Compile the file using javac command:

javac FloatingNumbers.java

Run the program

Run the program using the java command:

java FloatingNumbers

You will see the output as:

Value is infinite
Value is not NaN

Summary

In this lab, we learned about the isInfinite() method of the Float class in Java, which is used to check whether a floating-point value is infinite or not. We also learned how to use the isNaN() method to check whether the float value is not a number or not.

Other Java Tutorials you may like