문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top