Unveiling the Depths: Shallow Copy vs. Deep Copy in Java

Naveen Metta
4 min readJan 10, 2024
credit goes to the owner : https://algodaily.com/lessons/special-methods-and-concepts-oop/shallow-deep-copy
source : algodaily.com

Introduction:

In the intricate world of Java programming, understanding the concepts of shallow copy and deep copy is paramount for crafting robust and efficient code. Shallow copy and deep copy refer to different ways of duplicating objects, each with its own implications for data integrity and memory management. Let’s delve into the depths of these concepts, exploring their nuances and providing concise code examples to illuminate their usage.

Shallow Copy:

What is Shallow Copy?

Shallow copy involves creating a new object and copying the contents of the existing object to the new one. However, the references within the new object still point to the same objects as the original. In other words, it copies the values of the primitive data types and the references to complex types, but not the actual objects.

How to Perform Shallow Copy in Java:

Shallow copy is often achieved through the copy constructor or by manually replicating the fields of an object. Let’s explore the copy constructor approach:

public class ShallowCopyExample {
public static void main(String[] args) {
// Original object
Person originalPerson = new Person("John", new Address("123 Main St"));

// Shallow copy using copy constructor
Person shallowCopyPerson = new Person(originalPerson);

// Modifying the shallow copy
shallowCopyPerson.setName("Jane");
shallowCopyPerson.getAddress().setStreet("456 Side St");

// Original object remains unchanged
System.out.println("Original Person: " + originalPerson);
System.out.println("Shallow Copy Person: " + shallowCopyPerson);
}
}

In this example, we have a Person class with a copy constructor that performs a shallow copy. The modification of the address in the shallow copy also affects the original person’s address, showcasing the shared reference.

Deep Copy:

What is Deep Copy?

Deep copy involves creating a new object and recursively copying all the objects referenced by the original object, ensuring that the new object is entirely independent of the original. This approach results in a duplication of the entire object hierarchy.

How to Perform Deep Copy in Java:

Deep copy can be achieved using serialization, custom copy methods, or third-party libraries. Let’s focus on the serialization approach:

import java.io.*;

public class DeepCopyExample {
public static void main(String[] args) {
// Original object
Person originalPerson = new Person("John", new Address("123 Main St"));

// Deep copy using serialization
Person deepCopyPerson = deepCopy(originalPerson);

// Modifying the deep copy
deepCopyPerson.setName("Jane");
deepCopyPerson.getAddress().setStreet("456 Side St");

// Original object remains unchanged
System.out.println("Original Person: " + originalPerson);
System.out.println("Deep Copy Person: " + deepCopyPerson);
}

@SuppressWarnings("unchecked")
private static <T> T deepCopy(T object) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos)) {

// Writing the object to a byte array
out.writeObject(object);

try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis)) {

// Reading the object from the byte array
return (T) in.readObject();
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("Deep copy failed", e);
}
}
}

In this example, the deepCopy method utilizes object serialization to create a new object with an independent copy of the entire object hierarchy. Serialization provides a generic and flexible way to perform deep copy operations.

When to Use Shallow Copy:

Pros and Cons of Shallow Copy:

Shallow copy has its own set of advantages and limitations:

Pros:
Simplicity: Shallow copy is straightforward to implement, requiring minimal code.
Efficiency: It can be more efficient than deep copy, especially for large and complex objects.

Cons:

Shared References: Modifications to shared references in the copied object impact the original object, leading to potential unintended side effects.

Limited Independence: Shallow copy does not provide full independence between the original and copied objects.

When to Use Deep Copy:

Pros and Cons of Deep Copy:

Deep copy, while powerful, comes with its own considerations:

Pros:

Independence: Deep copy creates fully independent copies, ensuring modifications do not affect the original object.

Data Integrity: It is particularly useful when dealing with complex object hierarchies to maintain data integrity.

Cons:

Complexity: Implementing deep copy can be intricate, involving recursion and careful consideration of object relationships.

Resource Intensive: Deep copy, especially for large object hierarchies, can be resource-intensive in terms of memory and processing.

Real-world Considerations:

Choosing the Right Approach:

The choice between shallow copy and deep copy depends on the specific requirements of the application:

Shallow Copy Use Cases:

When a simpler and more efficient copying mechanism is sufficient.
In scenarios where shared references are acceptable and modifications to the copied object won’t impact the original.

Deep Copy Use Cases:

When complete independence between the original and copied objects is crucial.
Dealing with complex object hierarchies where maintaining data integrity is paramount.

Performance Considerations:

Striking the Right Balance:

While the performance of both shallow and deep copy depends on the specific use case, developers should consider the following:

Benchmarking: Conduct performance benchmarks to evaluate the impact of copying mechanisms on application performance.

Optimizations: Explore optimization techniques, such as custom copy methods or third-party libraries, to enhance the efficiency of deep copy operations.

Conclusion:

In the realm of Java programming, the distinction between shallow copy and deep copy is crucial for maintaining data integrity and managing memory efficiently. Shallow copy offers simplicity but comes with the risk of shared references, while deep copy ensures independence at the cost of complexity. Armed with a nuanced understanding and practical examples, Java developers can navigate the intricacies of object duplication, choosing the most suitable approach based on their specific use cases.

As you embark on your coding journey, may your copies be precise, and your objects stand resilient in the face of manipulation. Remember, the art of copying objects is not merely a technical endeavor; it’s a strategic choice that shapes the resilience and robustness of your Java applications. Happy coding!

--

--

Naveen Metta

I'm a Full Stack Developer with 2.5 years of experience. feel free to reach out for any help : mettanaveen701@gmail.com