Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (Integer) 222 != (Integer) 222 in Java? [duplicate]

It holds true for (Integer) 1 == (Integer) 1, which seems legitimate.

So why it's having excursion for (Integer) 222's equality?

like image 364
Snehal Masne Avatar asked Jul 11 '26 14:07

Snehal Masne


1 Answers

Integer is a class. So to compare objects you need to use equals instead of ==

What actually happens with shorter Integer is that if you get an Integer using the method valueOf you get always the same cached instance for values between -128 and 127. So in this case == works.

It doesn't work if you instead of using valueOf create a new instance explicitly with the operator new.


For To be more clear I write the current implementation of valueOf

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}
like image 76
Davide Lorenzo MARINO Avatar answered Jul 14 '26 02:07

Davide Lorenzo MARINO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!