What will the below code snippet print?

Integer foo1 = 1;
Integer foo2 = 1;
System.out.println(foo1 == foo2);

It prints true. This got me by surprise, as I thought it will print false, going by the object identity principles. The only way this can print true is, if foo1 and foo2 point to the same object. So, the question boils down to how are the objects foo1 and foo2 created? It certainly cannot be using the Integer(int) constructor because, then it cannot print true. The only other option is Integer.valueOf(int). To make sure I peeked at the class file created for the above code and voila there it was, Integer.valueOf(1).

So the above holds good only for integers in the range -128 to +127 as only Integer objects in this range are cached by the Integer class.

Advertisements