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.