Search code examples
javaprimitive

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'.


Solution

  • 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)