Integer x = 400;
Integer y = x;
x++;
At this point x is 401 and y is 400.But I think both are referring to the same object and both should be 401. I don't know how this is happening.please help.
Integer x = 400;
Integer y = x;
x++;
At this point x is 401 and y is 400.But I think both are referring to the same object and both should be 401. I don't know how this is happening.please help.
Because x++
is effectively the same as x = x + 1
. x + 1
is a different Integer
object, and x
is updated to refer to this other object.
Opcode says everything.
package wrapperInteger;
public class WrapperTest {
public static void main(String[] args) {
Integer x =400;
Integer y=x;
x++;
y--;
}
}
OPcode:
If you realized that x corresponds #16 and y corresponds #22. So it proves that both variables are pointing different objects.
Compiled from "WrapperTest.java"
public class wrapperInteger.WrapperTest extends java.lang.Object{
public wrapperInteger.WrapperTest();
Code:
0: aload_0
1: invokespecial #8; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: sipush 400
3: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
6: astore_1
7: aload_1
8: astore_2
9: aload_1
10: invokevirtual #22; //Method java/lang/Integer.intValue:()I
13: iconst_1
14: iadd
15: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
18: astore_1
19: aload_2
20: invokevirtual #22; //Method java/lang/Integer.intValue:()I
23: iconst_1
24: isub
25: invokestatic #16; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
28: astore_2
29: return
}
All wrapper classes in java are immutable
.So a new instance
of the object
creates each time.
Of course carrying different value for each instance.
Integer is immutable . So when you are copying some values to it it is creating a new instance of the object
Here In this image, when you increment value of X=X+1 then it will create new reference rather then pointing to same one.So after incrementing value of X, X will point to 401.And Y will point to 400 as Y is not incremented.