Why there is a difference in behavior for copying contents in primitive and non primitive type?

Vamsi K
Nov 9, 2020

--

Primitive & Non-Primitive Data types

In Primitive data types (i.e. Number, Boolean, String, etc.) the copying of variables is done in the form of copy by value.

Copy by value:

In primitive data types if we assign a variable to other variable, its data is passed to another variable and both of them refers to unidentical memory locations.

Example of copy by value in String data type

Whereas in Non-Primitive data types (i.e. Arrays, Objects, etc.) the copying of variables is done in the form of copy by reference.

Copy by reference:

In non-primitive data types if we assign a variable to other variable, no new memory is allocated instead a reference is created which is pointed to the memory of the first variable.

i.e. Both the variables are pointed to same memory location.

Example of copy by reference in array object

--

--

Vamsi K
Vamsi K

Written by Vamsi K

0 Followers

Just another techie

No responses yet