-2

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?

nhouser9
  • 6,730
  • 3
  • 21
  • 42
Barry
  • 1,585
  • 3
  • 22
  • 35
  • Should be noted that you should avoid boxed values as much as possible. Collections are about the only place in the wild that makes sense to have boxed values. – Qix - MONICA WAS MISTREATED May 04 '16 at 00:11
  • @Qix: Nullable values is the other useful case (and for those, there is now a new option in Optional --- which of course is also a boxed value). – Thilo May 04 '16 at 08:38
  • @thilo there are a select few cases where you need to null a primitive value. Point is, *really* ask yourself if what you're doing is being clever or if a nullable primitive value is *really* the proper solution. I can think of only one scenario where it's okay, and that's deserializable classes. – Qix - MONICA WAS MISTREATED May 04 '16 at 08:47

1 Answers1

0

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • 1
    But that's not something you should rely on, really. Don't use `==` to compare objects, even when it sometimes works. – Thilo May 04 '16 at 00:01
  • @Thilo I don't see any problem with relying on a feature that's explicitly documented. It may be a bit counterintuitive, but I guess it depends how it's used. – shmosel May 04 '16 at 00:02
  • It's not like this "feature" buys you anything. `equals` works much more reliably and does not form "bad habits". – Thilo May 04 '16 at 00:04