Fun with Integer constants in Java

Recently I ran into a strange issue in Java. I was creating Integer values and comparing them with == when I should have been using .equalsTo(). However, most of my tests worked!

In Java, object equality tests if the objects are exactly the same place in memory – if the objects contain the same data but are in different locations, == will return false. Confusing the two is a common mistake, but normally you’d expect everything to fail if you get this wrong.

However, it turns out that the first byte of Integer values are cached, so that two Integer objects with the same value match with == if and only if the value is between -128 and 127, inclusive.

This is not a new discovery (eg https://dzone.com/articles/java-integer-cache-why-integervalueof127-integerva) but I hadn’t heard of it before, and took a while to find it, so it seems worth noting.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *