EDIT: OK, OK, I misread. I\'m not comparing an int to an Integer. Duly noted.
My SCJP book says:
When == is used to compare a primitive to a
Integer i1 = 1;
Integer i2 = new Integer(1);
System.out.println(i1 == i2);
When you assign 1 to i1
that value is boxed, creating an Integer
object. The comparison then compares the two object references. The references are unequal, so the comparison fails.
Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 != i2);
Because these are initialized with compile-time constants the compiler can and does intern them and makes both point to the same Integer
object.
(Note that I changed the values from 1000 to 100. As @NullUserException points out, only small integers are interned.)
Here's a really interesting test. See if you can figure this out. Why does the first program print true
, but the second one false
? Using your knowledge of boxing and compiler time analysis you should be able to figure this out:
// Prints "true".
int i1 = 1;
Integer i2 = new Integer(i1);
System.out.println(i1 == i2);
// Prints "false".
int i1 = 0;
Integer i2 = new Integer(i1);
i1 += 1;
System.out.println(i1 == i2);
If you understand the above, try to predict what this program prints:
int i1 = 0;
i1 += 1;
Integer i2 = new Integer(i1);
System.out.println(i1 == i2);
(After you guess, run it and see!)