Question

I am confuse about autoboxing unboxing in java. Please see my following two progarm.

Integer x = 400;
Integer y = x;
x++; x--;
System.out.println((x==y));

The output is false. 
I known why the output is false. Because of autoboxing x.

Integer x = 100;
Integer y = x;
x++; x--;
System.out.println((x==y));

The output is true.
But the program is same as the upper. Why the output is true? 
Please explain me detail.

Thank you very much.

Was it helpful?

Solution

This is because Integers -128 to 127 are cached, so in second example x and y refer to the same Integer instance.

Integer x = 100;          // x refers to cached 100
x++; 

is equivalent to

int var = x.intValue();
var++;
x = Integer.valueOf(var);  // returns cached 100

See Integer.valueOf(int) API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top