File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why is this happening? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why is this happening?" Watch "Why is this happening?" New topic

Why is this happening?

Derek Mason

Joined: Oct 28, 2000
Posts: 13
I passed scjp exam long back but I still have a question!
How can this return true???
new Float(Float.NaN).equals(new FLoat(Float.NaN))
I thought comparison with NaNs always return false!
Douggie Fox

Joined: Jun 14, 2001
Posts: 19
It's because Double objects are immutable and as a result Java just puts 1 object into memory rather than 2. The comparison you're making is on object references not values.

Derek Mason

Joined: Oct 28, 2000
Posts: 13
If that were the case:
System.out.println(new Float(Float.NaN)==new Float(Float.NaN));
Would print true but it does not!
Denis Anoykin

Joined: Jun 11, 2001
Posts: 8
The object of Float class contains member with primitive type 'float'
Thus I think in case:
new Float(Float.NaN).equals(new FLoat(Float.NaN))
Java compares float primitives into the Float objects
And in this case:
System.out.println(new Float(Float.NaN)==new Float(Float.NaN));
Java compares refernces to Float objects. And there are different references.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
When in doubt, check the API:
for f1.equals(f2)
If f1 and f2 both represent Float.NaN, then the equals method returns true, even though Float.NaN==Float.NaN has the value false.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Why is this happening?
It's not a secret anymore!