top of page

Difference between shallow copy and deep copy

Writer's picture: Div PatelDiv Patel

In java, there are two type of cloning we can do:

  1. Shallow copy

  2. Deep copy


Shallow Copy: In shallow copy a new reference variable of the class is created and it points to the same memory location as the original object. So, in memory there is only one object with two reference variables.


Example:

For any class named Rectangle:


Rectangle obj2 = obj1;


This will create a new variable named obj2 but will still point to the same memory object.


Deep Copy: In deep copy a new object is created and all the values from the old object is copied to a new object. This will create 2 difference objects in memory which are independent from each other.


Example:

For the same Rectangle class we can create a deep copy using this code:


Rectangle obj3 = new Rectangle();

Obj3.length = obj1.length;

Obj3.breadth = obj1.breadth;


This method will create new Obj3 with same values as obj1 but with different memory location.


Here's a graphical representation of this created objects:



As we can see, the shallow copy still points to the same object in memory so any changes in obj2 will be affected to obj1 as well. But for Obj3 is a deep copy, so it has its own memory space and separate object.

7 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page