Java autoboxing and comparison of Objects using operators

1k views Asked by At

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?

1

There are 1 answers

1
alirabiee On BEST ANSWER

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.