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

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

java - Correct way of thinking about primitive assignment

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

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

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...