In Java, Deep Copy (or Deep Cloning) refers to the process of creating a completely independent copy of an object, including all the objects referenced within it. This ensures that any changes made to the cloned object do not affect the original object and vice versa. In deep copy:
Primitive fields: Are copied by value, just like in a shallow copy.
Non-primitive fields (objects, arrays, collections): Are copied by creating new objects rather than referencing the same ones.
Example 1: In this example, we will perform a Deep Copy using the clone() method.
Output
Original City: London
Copied City: London
After modification:
Original City: London
Copied City: Paris
Explanation:
The Address object is cloned separately within the Person class’s clone() method.
As a result, both p1 and p2 have independent copies of the Address object.
Changing p2.addr.city does not affect p1.addr.city, confirming that a deep copy was created.
Example 2: Deep Copy using Copy Constructor
Output
Original City: New York
Copied City: New York
After modification:
Original City: New York
Copied City: Los Angeles
Explanation: The copy constructor creates a new Address object instead of copying the reference, ensuring that the nested object is also cloned. Hence, changes made in p2 don’t affect p1.
Advantages of Deep Copy
Independent Objects: Changes in the copied object do not affect the original.
Safe for Nested Objects: Clones referenced objects to avoid shared references.
Prevents Side Effects: Modifying one object does not impact others.
Maintains Data Integrity: Original data remains unchanged.
Handles Complex Objects: Supports cloning objects with nested or mutable fields.
When to Use Deep Copy
When your object contains nested objects.
When you need to ensure complete data independence between the original and the copied object as shared references can cause unexpected side effects.