Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# Question on NAN

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486
Consider the following code:
Scenario : 1
Float f1 = new Float(Float.NaN);
Float f2 = new Float(Float.NaN);
System.out.println( ""+ (f1 == f2)+" "+f1.equals(f2)+ " "+(Float.NaN == Float.NaN) );

Prints : false true false

Scenario 2 :
Float f1 = 0.0f;
Float f2 = -0.0f;
System.out.println(f1.equals(f2)); //Prints false
System.out.println(-0.0f == 0.0f); //Prints true

Can anyone please explain why ?
Source : own

Thanks<br />Dinesh
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

27

Scenario 1:

a. f1 and f2 are different objects, so comparing them with == returns false.
b. The Javadoc documentation of Float.equals() explains why this is so - look it up.
c. Float.NaN is defined to be not equal to anything, not even to NaN.

Scenario 2:

a. Again, see the Javadoc documentation of Float.equals(), it also explains this special case.
b. Zero is zero, there are not two mathematically separate values of negative and positive zero, so it's not strange that this returns true.

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486
I willbe thankful to you
Krishnamoorthy Vuyala Muralidharan
Ranch Hand

Joined: Sep 13, 2005
Posts: 52
Hi Dinesh

Here is the link below with the clear explanation of the behaviour of the method equals() for the Float class.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Float.html#equals(java.lang.Object)

Hope this helps.

Greetings
Kris
Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
Originally posted by Dinesh Tahiliani:
I willbe thankful to you

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

27

Originally posted by Dinesh Tahiliani:
I willbe thankful to you

One important thing that any Java programmer must be familiar with is the Javadoc documentation of the standard Java classes.

Ranch Hand

Joined: Mar 21, 2007
Posts: 71

Scenarion 1
1 . f1 == f2 is false because they are refering to different objects .
2 . f1.equals(f2) true because they contain same data
3 . Flaot.Nan == Float.NaN is false because Two NaN are not same .

Scenarion 2
yoy shoul know that -0.0 = +0.0
1 . -0.0 == +0.0 is true .
2 . (new Float(-0.0)).equals(new Float(+0.0)) is false .

About NaN and -0.0 , +0.0 these are 2 special cases .

SCJP 5 ๑۩۞۩๑♥~~ My Life is My Creation ~~♥๑۩۞۩๑
Ranch Hand

Joined: Mar 21, 2007
Posts: 71
Scenario 1
1 . f1 == f2 is false because they are refering to different objects .
2 . f1.equals(f2) true because they contain same data
3 . Flaot.Nan == Float.NaN is false because Two NaN are not same .

Scenario 2
yoy shoul know that -0.0 = +0.0
1 . -0.0 == +0.0 is true .
2 . (new Float(-0.0)).equals(new Float(+0.0)) is false .

About NaN and -0.0 , +0.0 these are 2 special cases .