2

If I have

    Float f1 = 5.25f;
    Float f2 = 5.25f;

Then

    f1 == f2 

is false. Though

    f1.equals(f2);

is true. Why is it so, I thought that if the unboxing is executed, then f1 == f2 should compare

f1.floatValue() == f2.floatValue();

the same as

f1.equals(f2); 

should do. What is wrong?

UPDATE: No I see the answer, because Java compares references for Float objects too. I asked the question because I had

    Long l = 15l;
    Long l2 = 15l;

But the

    System.out.println(l == l2);

output was

    true

So I was misleaded, and thought that numeric type objects are compared by value when using ==. But I found, that comparison of small long values will return true, because small long values are cached!

Community
  • 1
  • 1
Dmitry Bakhtiarov
  • 373
  • 1
  • 5
  • 14
  • 9
    because they are objects and `==` compares references. – njzk2 Mar 03 '14 at 19:38
  • @njzk2 sounds like an answer to me :) – C.B. Mar 03 '14 at 19:38
  • 2
    There is no reason to unbox, as none of the arguments calls for a primitive comparison – njzk2 Mar 03 '14 at 19:39
  • 1
    For the same reason that comparing two equal String values with == can return false. Since they are both Float, no unboxing occurs. Why would it? – David Conrad Mar 03 '14 at 19:39
  • And why would u use `Float` class instead of primitive `float` data-type? – MeetM Mar 03 '14 at 19:40
  • possible duplicate of [Manipulating and comparing floating points in java](http://stackoverflow.com/questions/2896013/manipulating-and-comparing-floating-points-in-java) – Engineer2021 Mar 03 '14 at 19:42
  • Even if they were `float` and not `Float`, you generally should not use `==` to compare, unless you really, truly expect them to be *exactly* equal. – Hot Licks Mar 03 '14 at 19:43

2 Answers2

3

f1 and f2 are objects.

== compares references.

There is no reason to unbox, as none of the arguments calls for a primitive comparison

If you compare f1 == 3.0f or f1 == f2.floatValue(), there will be unboxing, because one og the operands is a primitive.

njzk2
  • 38,969
  • 7
  • 69
  • 107
0

Simply put:

  • == compares the references.
  • .equals compares the values.

The same is true for String(s) and all other objects.

Community
  • 1
  • 1
Peter Rasmussen
  • 16,474
  • 7
  • 46
  • 63