Java : Boxing and using ==

65 views Asked by At

Lets say i have something like

 int a = 100;
 int b = 100;
 Integer c = (Integer) a;
 Integer d = (Integer) b;

c == d results to true. Does that mean objects c and d point to the same Object in memory?

Can any one shed light here?

Do we create 2 objects c and d here? Are they different objects or same? == tells me that they are same objects.

I also read somewhere that casting doesn't create new objects. It's just a way of representing the same object. That makes sense if I am trying to cast lets say an Object to a Integer.

But what about this case, where there is no object in picture before (all we had is primitives) and we are trying to create Object c and d here?

1

There are 1 answers

3
shmosel On

Autoboxing works without casting. The reason you're seeing reference equality is because autoboxing internally calls Integer.valueOf() which caches certain values:

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.