Difference in behavior for copying contents in primitive and non primitive type

Ratan Deep Singh
2 min readNov 22, 2020

Hello everybody,
Here we are going to learn about the difference in behavior while copying contents in primitive and composite data type (non-primitive data type).

To understand the difference, lets dig into the concepts copy-by-value and copy-by-reference

COPY BY VALUE :

Copy by Value or Deep Copy

Here, the variable a is assigned to variable b.
What this does is, it allocates a new memory location to the variable b and assigns 20 to variable b as per the syntax in line 49 in screenshot.

This is also known as DEEP COPY which applies on only primitive data types such as number, string and boolean.

So, any changes in value of b does not affect the value of a as both sits in different memory location

COPY BY REFERENCE :

Copy by Reference or Shallow Copy

And again, in this example, the variable a is assigned to variable b.
In this case, no new memory location is allocated for variable b, instead it points towards the location of variable a.

This is also known as SHALLOW COPY which applies on only composite data types such as arrays and objects.

So, any changes in value of b affects the value of a.

Check out my other blog by clicking on below link to learn on how to overcome the problem of SHALLOW COPY and also to have a better understanding on copy by value and copy by reference.

https://singhratan.medium.com/how-to-copy-by-value-a-composite-data-type-71dd960ab5fc

Happy learning!
Ratan

--

--