Integer arithmetic in equals expression

93 Views Asked by At

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?

1

There are 1 best solutions below

0
Elvin Aliyev On

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.