I think this excerpt from the JLS answers your question

NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.

Ankit Garg wrote:I think this excerpt from the JLS answers your question

NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.

Hi Ankit,

Thanks for your reply.

But did not quite understand the last part of the paragraph.
They say, (x<y) == !(x>=y) will be false if x or y is NaN.
But this also applies to the following:

Say,

x = 0;
y = 1;

(x<y) -> 0 < 1 -> true
(x>=y) -> 0 >= 1 -> false
hence the lhs and rhs are not equal and hence (x<y) == !(x>=y) is false even though neither of them are NaN

If this is so, how come the two values in LHS and RHS are unequal?? The type of NaN is a primitive double, not an object reference..

The simple answer here is.... The IEEE floating point standard defines it as so -- NaN does not equal NaN. And Java is simply supporting the standard.

As a side note, the equals() method will report it as equal, if they are Double objects. This is in direct violation of the standard, and the JavaDoc states it as so. The reason this is necessary is because it will break the usability of the certain collections if NaN does not equal NaN.

Deepak Lal wrote:Hi Bert ,
Could you please give us an example atleast on NaN used with Double class.??

No offense here -- but you are a SCJP candidate. It would take less than a minute to create a method, that creates two Double instances (assigned to NaN), and test the equals() method. What is it that is preventing you from writing this simple example?