posted 12 years ago
When you assign a primitive to an wrapper class, such as Integer i = 123, that's autoboxing. The compiler inserts a call to Integer.valueOf(123), this, in turn, may create a new Object, or may simply return a reference to an object in the constant pool. The default for the constant pool is integers in the range -128..127, however, it can be configured at JVM startup with a command line parameter.
So, when you autobox an int in the range -128..127, you get an object from the pool, so the same int value there gets mapped to the same single Integer object. And when you autobox an int outside that range, a new Integer object is created each time.
HOWEVER, if you write your Java code correctly, you'll never need to know this. That is, if you want to see if two objects hold the same "contents" or "value", you must always use equals(). When you do that correctly, it won't ever matter whether the objects were cached or not.
The only time to use == is when you want to see if two references point to the same object, and there are not many use cases where that arises. The main one is as a shortcut in implementing equals()--the first step is often if (that == this) reutrn true; Other than that, there are precious few occasions when it is correct to use == for reference types.