0

Well this interesting problem came up today, in Java, if two Integer's are initialized to the same value, Java will have them point to the same memory location (I assume to save memory).

Integer x = 10;
Integer y = 10;
out.println(x.equals(y) + " " + (x==y));

This will output true true. Furthermore, we can set x and y to other numbers beside 10;

Integer x = -128;
Integer y = -128;
out.println(x.equals(y) + " " + (x==y));

And

Integer x = 127;
Integer y = 127;
out.println(x.equals(y) + " " + (x==y));

And these will also output true true. But if we set x and y to -129, they no longer point to the same memory location.

Integer x = -129;
Integer y = -129;
out.println(x.equals(y) + " " + (x==y));

This outputs true false, a very interesting aspect. I do not know why Integer's will point to different memory locations if outside of Byte range and I hope someone can shed some light on the subject.

hnefatl
  • 5,860
  • 2
  • 27
  • 49
Prime72
  • 11
  • 2

1 Answers1

0

As far as I know, modern JVM implementations have "singleton instances" for all integers from -128 to +128, similar to internalized strings; they are simply always existent on the heap, whether you want them or not. So boxing the int 5 into an Integer will not return a new Integer object, but the "singleton" instance of Integer with value 5 instead. As you observed, boxing 129 will yield an actually new instance, thus == returns false if you do it twice. It only works for boxed values from -128 to +128 because these are singletons under the hood for efficiency reasons.

However, I'm not sure that this is part of any language or platform specification. It is simply a performance optimization, an implementation detail. Never rely on it in your code. Use equals() on boxed classes, never == even though it "appears to work".

Martin Häusler
  • 6,544
  • 8
  • 39
  • 66