when you compile a number literal in java and assign it to a Integer (capital I) the compile emits
Integer b2 =Integer.valueOf(127)
this line of code is also generated when you use autoboxing.
valueOf is implemented such that certain numbers are "pooled" and it returns the same instance for values smaller than 128.
from the java 1.6 source code, line 621:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
the value of high can be configured to another value, with the system property
-Djava.lang.Integer.IntegerCache.high=999
if you run your program with that system property, it will output true!!
the obvious conclusion: never rely on two references being identical, always compare them with .equals() method.
so b2.equals(b3) will print true for all logically equal values of b2,b3.
note that is Integer cache is not there for performance reasons, but rather to comform to the JLS, section 5.1.7, that object identity must be given for values -128 to 127 inclusive.