-1
public class test{
    public static void main(String[] args) {
        Integer i = new Integer(400);
        Integer x = i;
        i = i + 1;
        x == i;   
    }
}

Can anybody help me to understand the memory's changed about heap and stack. If x == i compares memory's address ?

Tianxin
  • 177
  • 11

2 Answers2

3

The only line which is not self-explanatory here is:

i = i + 1;

Because of autoboxing, this line is actually equivalent to:

i = Integer.valueOf(i.intValue() + 1);
                      ^ auto-unboxing
            ^ autoboxing

So the intValue of i is moved to the stack; 1 is added; then a new instance of Integer may be created on the heap (since values as high as 401 are not guaranteed to be cached by Integer internally).

As for x == i: assuming you mean something like

System.out.println(x == i);

That would always print false, since x and i are different instances.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

example: i point to address a1; x = i means x point to address a1; i = i + 1 means x point to address a2; so x == i will return false as a1 doesn't equals a2.