Newbie Java question. With the line commented out as shown, the output is
X is 10 Y is 10 EQ true
With the line un-commented the output is
X is 10 Y is 10 EQ false
It appears the assignment causes a new object to be internally created? Can someone please explain why the results are different?
public class Test {
public static void main(String args[]) {
Integer x = new Integer(10);
Integer y = x;
// y = 10;
System.out.println("X is " + x + " Y is " + y + " EQ " + (x==y));
}
}
>Solution :
In the first line, you explicitly create an Integer object.
In the second line, you assign a reference to that same object to y.
In the third line (when not commented out) you assign the int primative 10 to an Integer reference. Java automatically boxes that primitive, using Integer.valueOf. This caches values from -128 to +127, but that cache only works within the actual valueOf calls. It does not factor in any other, explicitly-created Integers, such as the one you created in line 1. As such, valueOf returns a different object, whose logical value is the same as the one you created in the first line (ie, 10).
Finally, you use == to compare the two Integer objects, which tells you not whether they are logically "equal", but whether they are the same object — which they’re not.