I just thought of this question: Using Java
int x = 1
int y = x;
x = 5;
why doesn't y = 5
now?
I just thought of this question: Using Java
int x = 1
int y = x;
x = 5;
why doesn't y = 5
now?
Because y
is a separate variable to x
, albeit initialised with the original value of x
.
y
is not a reference to x
, or a reference to the same object as x
. (int
is a primitive type in Java).
int x = 1
int y = x;
x = 5;
primitive value is copied on this line int y=x;
This is not copy of reference of an object which x
is pointing to.
For reference : http://javarevisited.blogspot.hk/2015/09/difference-between-primitive-and-reference-variable-java.html Is Java "pass-by-reference" or "pass-by-value"?
int x = 1; //Some memory is initialized(say at location ox00001) and x is pointing to that
int y = x ; //Some memory is initialized(say at location ox00050) and value of x is copied to that memory
x = 5 ; //value of memory location of x (i.e. ox00001) is changed to 5 but is not impacting memory location of y
But in case of Non-Primitive data type it shares memory location instead of data.
For reference http://javarevisited.blogspot.in/2015/09/difference-between-primitive-and-reference-variable-java.html
Take out two pieces of paper.
Write "x" on one, and "y" on the other.
Now write "1" on the paper you labelled "x". (int x = 1;
)
Then take the number you see on the "x" paper and write that same number on the "y" paper. (int y = x;
)
Then erase the number on the "x" paper and write "5" there instead. (x = 5;
)
Observe that the number on the paper you labelled "y" did not change.
Variables work exactly like that.