52

I know that '==' doesn't work with values outside the range of [-128,127] as there is a cache maintained of Integer objects within this range and the same reference is returned if value is within the range. But why does '>', '<', '>=', '<=' give correct answers even outside the range ?

Integer a=150;
Integer b=150;
System.out.println(a==b); //returns false

Integer a=150;
Integer b=150;
System.out.println(a>=b); // returns true

Why is this happening ?

Gaurang Singhal
  • 436
  • 4
  • 12

1 Answers1

84

The <, >, <= and >= operators are only defined for primitive types. Therefore using them on wrapper types causes the compiler to unbox the objects into primitives.

This means

System.out.println(a>=b);

is equivalent to

System.out.println(a.intValue()>=b.intValue());

However, the == and != operators exist for both primitive types and reference types, so using them to compare two objects of primitive wrapper types compares the references instead of the primitive values they wrap.

As Holger commented, comparison of object references with == and != existed in the Java language before auto-boxing and auto-unboxing were introduced, but comparison with <, >, <= and >= was not supported for any reference types before auto-unboxing was introduced.

This means that in the early days of Java, the a>=b of your code snippet would not pass compilation (since a and b are not primitive numeric types). On the other hand your a==b snippet would still pass compilation and return false.

Changing the behavior of == and != for reference types that happen to be wrappers of numeric primitives would change the behavior of existing code, thus breaking backwards compatibility, which is probably the reason it wasn't done.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Thanks. I suppose this is also the case with '>=' and '<=' operators ? – Gaurang Singhal Jun 08 '17 at 06:01
  • 1
    @GaurangSinghal yes – Eran Jun 08 '17 at 06:02
  • 6
    It might be worth noting that the possibility to use `==` and `!=` for comparing references existed in Java before the introduction of auto-unboxing, so it was impossible to define them to compare unboxed values, as that would break compatibility. Without that legacy, defining a different operator for reference comparison would be possible and the cleanest solution. Unfortunately, that ship has sailed… – Holger Jun 08 '17 at 12:43
  • @Holger That's a good point. I'll add it to the answer. Thanks! – Eran Jun 08 '17 at 13:23
  • @Eran You're welcome – GingerHead Jun 09 '17 at 09:27