Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In this example,

int x = 5;
int y = x;
x = 4;

y will remain 5 because x is just being reassigned and it is not manipulating the object it used to refer to in anyway. My question is, is what I just said a correct way of thinking about it? Or is there a duplication of the memory stored in 'x' and that duplication is put in 'y'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
200 views
Welcome To Ask or Share your Answers For Others

1 Answer

Primitives, unlike objects, are stored directly inside the variable. That is, a variable of primitive type is not storing a reference to a primitive, it stores the primitive's value directly.

When one primitive variable is assigned to another primitive variable, it copies the value.

When you do

int x = 5; int y = x; x = 4;

x sets the value inside of it to 4, and y still has the value 5 because its value is separate.

The only way for one variable to be changed by a change to another variable, is if both variables are references to a 'mutable' object, and the object is mutated - since they both are looking at the same object, rather than their own copies, they both observe the same change. (Note for example that strings, being immutable, will never 'suddenly change', but arrays and collections can)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...