How can you compare NaN values?
Floating-point numbers are ordered from -∞, -y (negative finite nonzero values), -0, +0, +y, +∞. The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers.
The special number NaN (not-a-number) is unordered and has the following characters:
- The numerical comparison operators <, <=, >, and >= always return false if either or both operands are NaN.
- The equality operator == returns false if either operand is NaN.
- The inequality operator != returns true if either operand is NaN .
In particular, x != x is true if and only if x is NaN, and (x == y) will be false if x or y is NaN.
To verify a floating point value is NaN, use the Double.isNaN() method instead. The x == NaN will not work because "The equality operator == returns false if either operand is NaN". NaN is never equal to any other number, not even itself.
The wrapper classes such as Float and Double have the same behavior when using the above comparison operators. Comparing two NaN Float objects using Float.equals() will yield true even even though Float.NaN==Float.NaN has the value false. This is one of two special cases in Float class and described in Float class document. Such behavior make it possible to use an NaN Float object as a key in a HashMap. For example,
public class Program {
public static void main(String[] s){
Double a = new Double(Double.NaN);
Double b = new Double(Double.NaN);
if( Double.NaN == Double.NaN )
System.out.println("True");
else
System.out.println("False");
if( a.equals(b) )
System.out.println("True");
else
System.out.println("False");
}
}
The output is
False
True
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?