This works too ("on my machine"):
Integer a = 128, b = 128;
whereas this won't work:
Integer a = 127, b = 127;
Auto-boxing an int
is syntactic sugar for a call to Integer.valueOf(int)
. This function uses a cache for values from -128 to 127, inclusive. It may cache other values, but in my case, it doesn't.
Thus, the assignment of 128 doesn't have a cache hit; it creates a new Integer
instance with each auto-boxing operation, and the reference comparison a != b
is true. The assignment of 127 has a cache hit, and the resulting Integer
objects are really the same instance from the cache. So, the reference comparison a != b
is false.
What I really want to point out is to beware of reference comparison with auto-boxing. A more likely real-world problem is that you expect a == b
is true because they were assigned the same (auto-boxed) value, you run some unit tests that confirm your expectation, and then your code fails "in the wild" when some counter exceeds the upper limit of the cache. Fun times!