Java Data Type How to - Check if a Java Float is Infinite or Not a Number(NAN)








Question

We would like to know how to check if a Java Float is Infinite or Not a Number(NAN).

Answer

public class Main {
  public static void main(String[] args) {
    float f = (float) 1 / 0;
    boolean b1 = Float.isInfinite(f);
    System.out.println(b1);/* w  w  w  .  ja  v  a2s.  c o m*/

    Float fObj = new Float(f);
    boolean b2 = fObj.isInfinite();
    System.out.println(b2);
  }
}

The code above generates the following result.

public class Main {
/*from   www.  j a  va 2 s. c o  m*/
  public static void main(String[] args) {
    float f = (float) Math.sqrt(-10);
    boolean b1 = Float.isNaN(f);
    System.out.println(b1);

    Float fObj = new Float(f);
    boolean b2 = fObj.isNaN();
    System.out.println(b2);
  }
}

The code above generates the following result.