Hey all, I ran into an interesting occurrence and am looking for an explanation.
In Java 1.6:
Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b);
Integer c = 5;
Integer d = 5;
System.out.println(c == d);
I get:
false
true
In Eclipse I checked in the debugger. a and b are different objects, while c and d are the same objects (but different from a and b).
Can anyone clue me in on what’s going on under the hood? Is this JVM magic? Realizing that a Integer(5) is already on the stack?
Java caches
Integerinstances for values it deems close enough to zero if they’re constants. Manually creating anIntegerusingnewbypasses that cache. You can callInteger.valueOfwith anintto get the correspondingIntegerwithout bypassing the cache.You may want to search for “JVM Integer cache” on your search engine of choice for more information.