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 wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.
So you'd think this code would print true
:
Integer i1 = 1; //if this were int it'd be correct and behave as the book says.
Integer i2 = new Integer(1);
System.out.println(i1 == i2);
but it prints false
.
Also, according to my book, this should print true
:
Integer i1 = 1000; //it does print `true` with i1 = 1000, but not i1 = 1, and one of the answers explained why.
Integer i2 = 1000;
System.out.println(i1 != i2);
Nope. It's false
.
What gives?
Note also that newer versions of Java cache Integer
s in the -128 to 127 range (256 values), meaning that:
Integer i1, i2;
i1 = 127;
i2 = 127;
System.out.println(i1 == i2);
i1 = 128;
i2 = 128;
System.out.println(i1 == i2);
Will print true
and false
. (see it on ideone)
Moral: To avoid problems, always use .equals()
when comparing two objects.
You can rely on unboxing when you are using ==
to compare a wrapped primitive to a primitive (eg: Integer
with int
), but if you are comparing two Integer
s with ==
that will fail for the reasons @dan04 explained.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With