A bit-wise copy of an object is known as 'Shallow Copy'. When there is an original object, a new object is created where the same values as in the original object are copied.
Basically, there are two types of Data types given below:
We will understand its role in the shallow copy.
What is Shallow Copy
The shallow copy of an object refers to the reference location/address of the original object. In case any field of the object reference to the other objects, it copies only the reference address (i.e., the memory address) of the object and no new object is created. This is how a shallow copy is different from a deep copy. The shallow copy replicates the object's top-level properties, but the nested object is shared between the original and the copied one. A shallow copy only copies the collection structure and not the values. It means two collections share the elements of the original collection.
Generally, a shallow copy is easy and simple to use because no object is created, only the reference address is copied. Not only in the case of arrays, but the same applies to the arrays too.
Thus, in the case of primitive data types, when we create a copy of the primitive data type variable, the value is copied to a new memory address to which the new variable points. So, whenever we make a copy, it will create a new memory location and will be a real copy of the variable. Thus, if we execute c = a, then a copy of 'a' is created. So, if we try to assign a new value to c, the value of c will change, but it will not affect the value stored in variable a. It is because once initiated, values are stored for once.
In the case of reference data types, it stores the memory address of the object (i.e., location where the object is stored). Thus, copying of the values works well in the reference data types. So, both shallow and deep copies are types of reference data types only.
Now, we will try to understand Shallow copy with the help of an example.
Example of Shallow Copy
Consider two objects, obj1 and obj2, where obj2 reference to obj1. Hence, obj2 will copy the same memory address as the obj1, which means both the objects will have the same memory address and will point to the same address only.
You can see in the below diagram that represents the example well:
Example Code Implementation
Below we have mentioned a code example where we have created a shallow copy for the details of the student:
The output of the above code is shown below:
Thus, in this way, the shallow copy of one object can be created and used for assigning different values for the object properties.