Example
Let's say you create an array in Java:
int[] array1 = {1, 2, 3, 4, 5};
Now, we have our variable array1
that holds our anonymous array. You decide to create a second variable called array2
, and you set it equal to array1
.
int[] array2 = array1;
If we print our two arrays, we expect to get the same content, and that is what actually happens.
>>> [1, 2, 3, 4, 5]
>>> [1, 2, 3, 4, 5]
But, what if you want to change a number in array1
?, let's change our second index (number 3) to 9.
array1[2] = 9;
Again, let's print our two arrays.
>>> [1, 2, 9, 4, 5]
>>> [1, 2, 9, 4, 5]
Wow, why our second array has the number 9 as well?
This is the time when we have to look at the memory allocation, more specifically, the Stack and the Heap.
In java, data is classified in Reference and Primitive types, let's first look at how primitive types are saved in memory.
Primitive Types
Java supports eight primitive data types, which you can see here, i'll be using int
for the demo.
So imagine, we have the following code:
int x = 12;
int y = x;
Since these are primitive data types, both the variable and the value are saved on the stack, so when you declared y
to be equal to x
, what is going to happen is that the value from x
will get copied, and it will be saved in y
, in this case each variable has its own value now. If you wanted to change the value of y
, you would only be modifying that value for that variable.
y = 30;
Below, you have the visual representation:
Reference Types
Reference types hold references to objects and provide access to those objects stored somewhere in memory allocated on the heap, there are four kinds of reference types.
Let's go back to our example and explain it:
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = array1;
So, what's happening here?, as mentioned before, reference types hold references to the object, in this case, an array. The variable array1
is holding a reference in the stack, the variable is saved but this time, with the reference (imagine the reference as an arrow pointing to the object). As it happened before with primitive types, it copied the value from the variable to another, in this case the value we are copying is a reference, so now both array1
and array2
are pointing to the same object on the heap, that's why any change to one of the variables will reflect on the other.
Let's create an array just for array2
:
array2 = new int[5]; // Array of size 5
array2[1] = 9; // Updating the value of index 1
Now, array2
is pointing to a totally different object, and it's no longer pointing to the same object as array1
, when we now update a value of array2
, it won't affect array
.
Below, you have the visual representation:
And that's all! Hope you enjoyed this little post.
Top comments (0)