java Float: == equals compareTo

user1703055 picture user1703055 · Oct 25, 2012 · Viewed 7.7k times · Source

I have 2 questions.

1) I was told that when comparing two Float or Double data, use compareTo instead of equals. I don't know the reason. Is there any example that shows where using equals will lead something wrong?

2) See this code:

  float f2=(float)1.123450;
  Float f3=new Float(1.123450);

  System.out.println(f3==f2);   // result is true

I think using == means the two data point to the same memory address. But do f3 and f2 have the same address? Doesn't new Float(...) create a new space?

Answer

Ted Hopp picture Ted Hopp · Oct 25, 2012

If both arguments were reference types, then == would test memory locations. However, if one of the arguments to == (or !=) is numeric and the other is convertible to numeric (using unboxing), then the comparison is done by comparing numerical values after unboxing. So the comparison in this case is done on the basis of the floating point values (which in this case are identical). See the Java Language Specification §15.21.1 for details.

Note, however, that Float.NaN == Float.NaN is false.