0

I know the first expression evaluates to false because these are two distinct Integer objects.

I'm not sure why the second expression evaluates to true.

public static void main(String[] args)  {
   System.out.println(new Integer(1000)==new Integer(1000)); // false       
   System.out.println(new Integer(1000)==new Integer(1000)+new Integer(0)); // true
}

I suspect that the second expression evaluates to true because the right hand side first gets unboxed to an int and then gets compared to the left side. Is that true and if so, is this the defined behavior?

Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • 3
    Yes, `new Integer(1000)+new Integer(0)` needs to be unboxed for using the + operator. The result will be an `int` and the comparison then will need to unbox the left hand side as well. – Thomas Apr 07 '21 at 07:46
  • 1
    BTW `Integer.valueOf(1000)` would be correct coding style, even if it normally does not chache the Integer. – Joop Eggen Apr 07 '21 at 07:48

1 Answers1

0

Because new Integer(1000)+new Integer(0) return 1000 value. So java compare values of Integer. 1000==1000 is equals true. Bu first output is false because int this why java compare references of objects.