Video in progress

Strong Junior ⚙️ JVM and memory

Why does this code print true the first time and false the second? How does the Integer cache work?

Integer a = 127, b = 127;
System.out.println(a == b);   // true

Integer c = 128, d = 128;
System.out.println(c == d);   // false

Autoboxing goes through Integer.valueOf(), which returns a ready-made cached object for values from -128 to 127. At 127 both variables point to the same object; at 128 two separate objects are created and == compares references.

📖 Answer

Integer a = 127 actually compiles to Integer a = Integer.valueOf(127). Open it with javap -c and you will see invokestatic Integer.valueOf. Inside valueOf there is an IntegerCache: the objects from -128 to 127 are created once when the class loads and kept in an array.

That is why a and b are the same object, while c and d are two different objects. For wrappers, == compares references, not values.

Short, Long, Byte and Character (0..127) have similar caches. Double and Float do not.

You can raise the upper bound with a JVM flag:

java -XX:AutoBoxCacheMax=1000 -jar app.jar

But this only works for Integer, and it just hides the problem. The right way is to always compare wrappers with equals(), or unbox them to int first.

On prod this bug usually shows up like this: in testing the IDs are small (1, 2, 3) and everything works, then once IDs pass 128, if (order.getUserId() == currentUserId) suddenly starts returning false. IntelliJ and SpotBugs warn about this kind of comparison, so don't turn those warnings off.