Accessing by value and reference
Access by Value
If the value is a primitive value, when you access the variable, you manipulate the actual value stored in that variable. In other words, the variable that stores a primitive value is accessed by value.
Copying Primitive Values
When you assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable
The above works because we're accessing by value. We're copying the value to b
and b is a new address in the stack. a
and b
have no relationship, when you change the value stored in the b
variable, the value of the a
variable doesn't change.
Access by Reference
Unlike a primitive value, when you manipulate an object, you work on the REFERENCE of that object, rather than the actual object.
It means that a variable that stores an object is ACCCESSED BY REFERENCE
Copying by reference value
When you assign a reference value from one variable to another, the value stored in the variable is also copied in the location of the new variable.
THE DIFFERENCE is that the value stored in BOTH variables now are the ADDRESS of the actual object stored in the heap!
Last updated