Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can two wrapper objects be equal, yet not equal at the same time

I have this code:

class ABC
{
    public static void main(String[] args) {
        Integer inta = new Integer(10);
        Integer intb = new Integer(10);
        if (inta <= intb) {
            System.out.println("inta is less than intb");
        }
        if (inta >= intb) {
            System.out.println("inta is greater than intb");
        }
        if (inta != intb) {
            System.out.println("inta is not equal to intb");
        }
    }
}

This outputs:

inta is less than intb
inta is greater than intb
inta is not equal to intb

Can anyone explain why this happens? How can an object be equal and not equal at the same time?

like image 683
Jigar Avatar asked Feb 02 '26 01:02

Jigar


2 Answers

It satisfies the first and second ones because the compiler needs primitive types for greater-than (>) or less-than comparison (<) operations, so it makes an auto unboxing from Integer to int. Because you use the or-equal-to operators (<= and >=), the conditional is true.

It satisfies the third one because the compiler checks two Integer object to see if they are the same object, and since they are not, the conditional is true.

like image 167
Salih Erikci Avatar answered Feb 03 '26 15:02

Salih Erikci


Wrapper objects are still objects; if one performs object equivalence on them (==), then unless they're the exact same reference, that will always be false.

Unboxing happens because we're using relational operators, which will unbox to a type that can be respected by the operators - in this case, int. The comparison happens as if you didn't have the wrappers.

Things get interesting if you use the fact that Integer can be cached through the use of valueOf().

If your expression appeared as such:

Integer inta = Integer.valueOf(10);
Integer intb = Integer.valueOf(10);

...then performing inta == intb would equal true, since both values are between the cached range of [-128, 127].

Since you're attempting to see if a value is larger than, greater than, or equal to another, then consider using Comparable instead. An Integer is a Comparable entity, so you can simply do this:

System.out.println(inta.compareTo(intb) < 0); // to check for a < b
System.out.println(inta.compareTo(intb) == 0); // to check for a == b
System.out.println(inta.compareTo(intb) > 0); // to check for a > b
like image 44
Makoto Avatar answered Feb 03 '26 17:02

Makoto



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!