2
public class MyClass
{
    public static boolean isEqual(Object obj1, Object obj2)
    {
        return obj1==obj2;
    }

    public static void main(String args[])
    {
        //output: true
        System.out.println(2.2f==2.2f);
        //output: false
        System.out.println(isEqual(2.2f,2.2f));
        //output: true
        System.out.println(22L==22L);
        //output: true
        System.out.println(isEqual(22L,22L));
    }
}

All of the following print statements except the second output true. Why is this so? The method isEqual() call for two integer literals outputs true yet the call for two floating point literals outputs false, but why? And why does this operates differently from the regular == comparison?

NoobsPwnU
  • 37
  • 5

1 Answers1

3

Your method isEqual() expects Objects as arguments. So the primitive longs and floats are boxed, and the created Long/Float instances are passed as argument. This internally calls the methods Long.valueOf()/Float.valueOf().

Your implementation of Long.valueOf() caches some values and returns cached values (it's allowed, but not required to do so, unlike Integer.valueOf() which is required to return cached values for the range -128 to 127)). So Long.valueOf(22L) == Long.valueOf(22L). That's just not the case with Float.valueOf().

Try with larger long values, and the comparison will be false.

You should never compare objects using ==, except if they are enums. Use equals().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255