So I was asked this question today.
Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer d = a + b;
System.out.println(c == d);
What will this program print out? It returns true. I answered it will always print out false because of how I understood auto (and auto un) boxing. I was under the impression that assigning Integer a = 3 will create a new Integer(3) so that an == will evaluate the reference rather then the primitive value.
Can anyone explain this?
This is what is really happening:
Java maintains a cache of
Integer
objects between -128 and 127. Compare with the following:Which should print
false
.It's because some of the (auto-boxed) Integers are cached, so you're actually comparing the same reference -- this post has more detailed examples and an explanation.
Caching happens outside of autoboxing too, consider this:
this will print:
So I guess that generally you want to stay away from '==' when comparing Objects
Boxed values between -128 to 127 are cached. Boxing uses
Integer.valueOf
method, which uses the cache. Values outside the range are not cached and always created as a new instance. Since your values fall into the cached range, values are equal using == operator.Quote from Java language specification:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7