Correct way of thinking about primitive assignment

前端 未结 3 484
后悔当初
后悔当初 2020-12-21 06:09

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 u

相关标签:
3条回答
  • 2020-12-21 06:33

    primitive variables actually hold the value (not the reference). So at any point of time you create a primitive variable, a memory block (of that primitive type) gets reserved for a value, no matter you have assigned a value for that or not.

    (in any low level language you can think of a variable as a register)

    0 讨论(0)
  • 2020-12-21 06:35

    There are 2 separate location for the x and y. x and y here are primitives not objects.

    When you do

    int y = x;
    

    A separate memory for int variable y is created and the value of x i.e 5 is copied into that location.

    after this, if you reassign any other value to the variable x by doing :

    x = 4;
    

    , it does not reflect in the value of y.

    Even if you use Wrapper class Integer it will behave in the similar fashion, since these are immutable classes. for example:

    Integer x = new Integer(5);
    Integer Y = x; //now both `x` and `y` point to the same `integer` object with the value 5.
    x= new Integer(4); // now since `x` is pointing to a different object than `y`, both `x` and `y` remain independent(i.e change in one does not reflect in another).   
    
    0 讨论(0)
  • 2020-12-21 06:37

    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)

    0 讨论(0)
提交回复
热议问题