java - Correct way of thinking about primitive assignment -
in example,
int x = 5; int y = x; x = 4;
y remain 5 because x being reassigned , not manipulating object used refer in anyway. question is, said correct way of thinking it? or there duplication of memory stored in 'x' , duplication put in 'y'.
primitives, unlike objects, stored directly inside variable. is, variable of primitive type not storing reference primitive, stores primitive's value directly.
when 1 primitive variable assigned primitive variable, copies value.
when do
int x = 5; int y = x; x = 4;
x
sets value inside of 4, , y
still has value 5 because value separate.
the way 1 variable changed change variable, if both variables references 'mutable' object, , object mutated - since both looking @ same object, rather own copies, both observe same change. (note example strings, being immutable, never 'suddenly change', arrays , collections can)
Comments
Post a Comment