Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cache and equality

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 ++?

like image 724
user986688 Avatar asked Jan 16 '23 04:01

user986688


1 Answers

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.

like image 129
Daniel Fischer Avatar answered Jan 17 '23 18:01

Daniel Fischer