2

I am trying to understand the behavior of below code when Numerical Comparison Operators are used to compare 2 Integer objects in Java.

    Integer i1 = new Integer(1);
    Integer i2 = new Integer(1);
    System.out.println(i1 == i2);
    System.out.println(i1 > i2);
    System.out.println(i1 >= i2);

Output of the above code is :

false
false
true

I understand what is happening in the 1st case (the comparison of object instance is made thats why it gives false). But why second and third scenario are different and how does it work exactly?

Ayushi Jain
  • 828
  • 8
  • 17
  • I'm confused by your result. I thought `Integers` in the range -128 to 127 were required by the JLS to be cached and the same object. https://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127 – markspace Sep 01 '17 at 18:00
  • @markspace Only when autoboxing or calling `valueOf()`. Objects created with the `new` keyword must always be distinct. – shmosel Sep 01 '17 at 18:03
  • @shmosel Ah, right! The SO question I linked to says "boxed" object. Thanks for point that out. – markspace Sep 01 '17 at 18:04
  • @shmosel - I don't understand how does https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java answers this question. This link doesn't talk about comparison of objects using operator. – Ayushi Jain Sep 01 '17 at 19:32
  • It does, briefly. *The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type* - meaning the operands are treated as numbers, not objects. – shmosel Sep 01 '17 at 19:35
  • Ok Thanks got it !! Seems logical after knowing the answer but initially it didn't seem to be self explanatory. – Ayushi Jain Sep 01 '17 at 22:14

1 Answers1

7

Because <, >, >=, and <= are numerical comparison, and thus, the compiler knows it has to do unboxing.

However, == and != always work as reference comparators for non-primitive types.

alirabiee
  • 1,286
  • 7
  • 14
  • Binary numeric promotion (conversion to numeric) is performed on the <, <=, >, and >= operands as specified in ([JLS 15.20.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.1)) for the 2nd and 3rd scenario. However in case of != and == at least one of the operand have to be of numeric type for the promotion to happen. – Ayushi Jain Sep 07 '17 at 17:00