This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equal() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equal()" Watch "equal()" New topic


Tony kunds

Joined: Apr 25, 2002
Posts: 25
Double d=new Double(0.9);
Float f= new Float(0.9f);
why is f.equals(d) returns false.
I know that equals()test for value.
if double d=0.9;
float f=O.9f;
d==f returns true.
why when the value of object is checked it returns false.
I think I am missing some thing.Please point it out.
Dave Wingate
Ranch Hand

Joined: Mar 26, 2002
Posts: 262
In this case, equals() returns false because you are comparing objects of two different types.
Many implementations of the ClassType.equals(object x) method say something like:
"Only return true if and only iff x is instance of ClassType and . . . "
Remember you're not using equals() to compare th values wrapped by the wrapper classes. You are comparing the objects.

Fun programming etcetera!
swapna sivaraju
Ranch Hand

Joined: Jan 18, 2002
Posts: 75
HI Tony,
In ur code:
Double d=new Double(0.9);
Float f= new Float(0.9f);
d and f are two different types of objects one is of type Double and other Float and hence the tyoe of value they represent is different.Thats why
f.equals(d) returns false ..
Now secondly,
double d=0.9;
float f=O.9f;
d==f returns true.
for == operator the binary numeric promotion is applied and so when we compare double and float ..the value
of float (0.9f) gets promoted to double ..
so u get the answer as true.
This type of automatic conversion is not applicable to Object types (here it is Double and Float).
I hope u get it.

Ana P

Joined: May 02, 2002
Posts: 10
double d=0.9;
float f=0.9f;
System.out.println("d==f " + (d==f));
I tried this , but got answer d==f as false
Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
If d had been initialized as
double d = 0.9f;
then it would have printed true.


best regards,<br />Steven<br />SCJP, SCEA
Ana P

Joined: May 02, 2002
Posts: 10
double d21=10.3;
float f21=10.3f;
System.out.println("d==f " + (f21==d21));
This does not return true for all values
like 0.9. 0.5
I think while promotion it loses precision.
am i right?
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

"Ana P"-
Welcome to the JavaRanch! Please adjust your displayed named to match the JavaRanch Naming Policy. You can adjust it here.
Thanks! and welcome to the JavaRanch!
I agree. Here's the link:
subject: equal()
It's not a secret anymore!