Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
I have a question about the memory management in Java.
When I try the following code:
Integer a = 1;
Integer b = 1;
System.out.println(a==b); // this gives "true"
However,
Integer a = 256;
Integer b = 256;
System.out.println(a==b); //this gives "false"
Why?
Thanks very much.
That is because “autoboxing” uses
Integer.valueOf, andInteger.valueOfkeeps a cache ofIntegerobjects for small integer values. Here’s what the JLS says:When you use the
==operator to compare a pair ofIntegerobjects, it is actually comparing the object references. So your gettrueif boxing gave you the same cachedIntegerobject, andfalseif it didn’t. Note that the JLS guarantees this behaviour for the ranges stated, but it also permits an implementation of thevalueOfmethod to cache a wider range of values.The bottom line is that you should use
equals(Object)to compareIntegerobjects … unless you are really trying to test if they are the same object.If your code explicitly does a
new Integer(...), it is guaranteed to create a newIntegerobject. However, autoboxing usesInteger.valueOf(...), and that is where the caching behaviour is implemented.