Video in progress
Why does comparing two Integers with == sometimes give true and sometimes false?
Integer a = 100, b = 100;
Integer c = 1000, d = 1000;
System.out.println(a == b);
System.out.println(c == d);
Integer.valueOf caches values from -128 to 127 and returns the same object, so == gives true. Outside that range a new object is created each time, and == compares references and gives false.
📖 Answer
The output:
true
false
Autoboxing calls Integer.valueOf(...). It takes small numbers from a ready cache:
100comes from the cache, soaandbare one object;1000gets a new object for each variable, so==is false.
That's why the bug can stay hidden in tests: the ids in test data are small, but in prod the id is 52,431, and suddenly the comparison stops working.
The right ways:
c.equals(d); // true
Objects.equals(c, d); // null-safe
c.intValue() == d.intValue();
The same applies to Long, Short, Byte and Character (0-127). You can raise the cache limit with -XX:AutoBoxCacheMax, but relying on that just hides the bug.
Sign up to mark studied questions and save your progress.