Java cache and equality

caching, equality, integer, java, object

Solution

After the increment, they are reboxed using `Integer.valueOf()`, and for small absolute values (between `-128` and `127` by default), that uses the cached instances.

Problem

I've been reading over java caches for class and I'm not exactly sure why this code works. ``` Integer x = new Integer(2); Integer y = new Integer(2); assert x != y; assert x.intValue() == y.intValue(); ++x; assert x != y; assert x.intValue() != y.intValue(); ++y; assert x == y; assert x.intValue() == y.intValue(); ``` I understand that initially x and y are not equal because they reference different objects, but why do they become equal after the ++?

Original source