0

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
TooCool
  • 10,598
  • 15
  • 60
  • 85

2 Answers2

7

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
2

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

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142