Human
Human

Reputation: 10815

Why boxed primitives doesn't support all operators?

After watching the Effective Java video I noticed that boxed primitives types support only four of the six comparison operators which <, >, <=, >= and don't support == and !=.

My question is why boxed primitives don't support all operators?

Upvotes: 0

Views: 72

Answers (2)

They do support == and !=. They just don't do what you're expecting.

For references, == and != tell you whether two references are equal - that is, whether they refer to the same object.

class Thingy {}
Thingy a = new Thingy();
Thingy b = new Thingy();
System.out.println(a == b); // prints false, because a and b refer to different objects

Thingy c = b;
System.out.println(b == c); // prints true, because b and c refer to the same object

This applies to all reference types, including boxed primitives:

Integer a = new Integer(50);
Integer b = new Integer(50);
System.out.println(a == b); // prints false, because a and b refer to different objects

Integer c = b;
System.out.println(b == c); // prints true, because b and c refer to the same object

Now, references don't support < or > or <= or >=:

Thingy a = new Thingy();
Thingy b = new Thingy();
System.out.println(a < b); // compile error

however, boxed primitives can be auto-unboxed, and the unboxed primitives do support them, so the compiler uses auto-unboxing:

Integer a = new Integer(42);
Integer a = new Integer(43);

System.out.println(a < b);
// is automatically converted to
System.out.println(a.intValue() < b.intValue());

This auto-unboxing doesn't happen with == or !=, because those operators are already valid without auto-unboxing - they just don't do what you expect.

Upvotes: 7

Mike Nakis
Mike Nakis

Reputation: 61993

Because in java the == and != operators always do comparison of objects by reference, and boxed types are objects.

Upvotes: 2

Related Questions