Shallow Copy vs Deep Copy in Java

In this post, we will learn the difference between Shallow Copy and Deep Copy in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between Shallow Copy and Deep Copy in Java

Feature Shallow Copy Deep Copy
Definition A shallow copy creates a new object, but it does not create new instances of the object's non-primitive fields. Instead, it copies references to the same objects in memory. A deep copy creates a new object and also creates new instances of all the object's non-primitive fields. It recursively copies the entire object graph, including all the objects referenced by the original object.
Contents The shallow copy and the original object share the same non-primitive fields. Changes made to these fields in one object are reflected in the other. The deep copy and the original object have separate copies of all non-primitive fields. Changes made to these fields in one object do not affect the other.
Memory Allocation A shallow copy requires less memory because it only duplicates references to existing objects. A deep copy requires more memory because it creates new instances of all the non-primitive fields.
Performance A shallow copy is faster to create than a deep copy because it involves copying only references. A deep copy can be slower to create, especially for complex object graphs, as it involves recursively copying multiple objects.
Nested Objects A shallow copy does not create copies of nested objects. It only copies references to them. A deep copy creates separate copies of all nested objects, including those nested multiple levels deep.
Dependency on Object Structure A shallow copy depends on the structure of the object. If an object contains references to other objects, those references will also be shared. A deep copy is independent of the object's structure. It creates new copies of all objects in the object graph, regardless of how they are referenced.
Implementation A shallow copy can be achieved using the Object.clone() method or manually copying references to fields. A deep copy usually requires custom implementation using serialization, copy constructors, or third-party libraries.


Comments