Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Question on NAN

Dinesh Tahiliani
Ranch Hand
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

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
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
Posts: 486
I willbe thankful to you

Krishnamoorthy Vuyala Muralidharan
Ranch Hand
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
Posts: 165
Originally posted by Dinesh Tahiliani:
I willbe thankful to you

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
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
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 .

Ranch Hand
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 .