0% found this document useful (0 votes)
10 views9 pages

Shallow vs Deep Copy in Java Explained

The document discusses the differences between shallow and deep copying in Java, emphasizing the importance of understanding object copying due to Java's reference-based nature. Shallow copies share references of nested objects, while deep copies create completely independent objects, impacting performance, memory usage, and thread safety. It also highlights best practices for implementing these copying methods and the implications for software design and concurrency.

Uploaded by

adin
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Shallow vs Deep Copy in Java Explained

The document discusses the differences between shallow and deep copying in Java, emphasizing the importance of understanding object copying due to Java's reference-based nature. Shallow copies share references of nested objects, while deep copies create completely independent objects, impacting performance, memory usage, and thread safety. It also highlights best practices for implementing these copying methods and the implications for software design and concurrency.

Uploaded by

adin
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Shallow Copy vs Deep Copy in Java

🔹 Why Object Copying Matters in Java


Java is a reference-based language. When objects are assigned or passed to methods, references are
shared, not the actual objects. This behavior often leads to:

Unintended data modification


Side effects across layers
Thread-safety issues
Hard-to-debug production bugs
Object copying exists to control how much state is shared between objects.

🔹 Reference Copy vs Object Copy

This is not a shallow copy or deep copy.


It is a reference copy.
Both variables point to the same object in memory.
Any change via p2 directly affects p1.
Object copying begins only when a new object is created.

🔹 Java Pass-By-Value Clarification


Java is strictly pass-by-value.
When objects are passed to methods, a copy of the reference is passed, not the object itself.
This explains why multiple variables can modify the same object.

Shallow Copy
🔹 Conceptual Understanding
A shallow copy creates a new object but copies references of nested objects instead of duplicating
them.

Primitive fields → copied

Reference fields → shared

The top-level object is new, but the internal structure is partially shared.

🔹 Copy Depth & Object Graph Complexity


Copying is not binary (shallow vs deep).
Objects form graphs that may be shallow, deep, or cyclic.

Shallow copy duplicates only the top-level object.


Deep copy depth depends on how far nested objects are copied.

The deeper the object graph, the more expensive and risky deep copy becomes.

🔹 Real-World Example (Enterprise Context)


Scenario:

An HR system creates a temporary employee profile for review, assuming changes won’t affect the
original record.

Code:

Usage:
Explanation:

Although e1 and e2 are different objects, both share the same Address reference. Modifying the
address through e2 affects e1.

This behavior is often unexpected and dangerous in real systems.

🔹 equals() / hashCode() Impact


Shallow copy can cause two objects to share internal state while appearing logically independent.
This can break equals() and hashCode() contracts, leading to issues in HashMap, caching, and
ORM dirty checking.

🔹 Where Shallow Copy Is Appropriate ?


Shallow copy is not inherently bad. It is useful when:

Objects are immutable


Nested objects are read-only
Performance is critical
Data is not meant to be modified

Examples:

Configuration snapshots
DTOs used only for reading
Cached immutable objects

🔹 Risks of Shallow Copy


Shared mutable state

Hidden side effects

Concurrency issues

Accidental data corruption

Most production bugs related to object copying come from unintended shallow copies.

Deep Copy
🔹 Conceptual Understanding
A deep copy creates:

A new object
New copies of all nested objects
Completely independent references
No part of the object graph is shared.

🔹 Real-World Example (Production-Grade)


Scenario:

A financial system processes transactions where historical customer data must remain unchanged.

Code:

Usage:

Explanation:

Each object owns its own state.


No changes in c2 can affect c1.

This behavior is safe, predictable, and production-ready.

🔹 ORM / JPA / Hibernate Perspective


JPA entities are persistence-context managed and proxy-based.
Deep copying entities can break change tracking and cause LazyInitializationException.

In enterprise systems, entities should not be deep copied.


DTOs should be used instead.

🔹 Shallow Copy vs Deep Copy - Architectural Comparison


Aspect Shallow Copy Deep Copy

Object independence Partial Complete

Nested object sharing Yes No

Performance High Moderate

Memory usage Low High

Thread safety Risky Safer

Debugging Difficult Easier

🔹 Diagram of shallow copy and deep copy


🔹 Why Both Exist ?
Using deep copy everywhere:

Wastes memory
Reduces performance
Increases complexity

Using shallow copy blindly:

Introduces subtle bugs


Breaks data integrity
Correct design means choosing the right depth of copying based on context.

🔹 Deep Copy Implementation Approaches in Java


Copy Constructors (Preferred):

Explicit intent
Type-safe
High performance

Recommended in enterprise systems

Clone with Manual Deep Copy:


Error-prone
Hard to maintain
Often misused

Serialization-Based Copy:

Slow
Memory intensive
Not suitable for production

🔹 Interview-Relevant Insights
clone() performs shallow copy by default
Cloneable is discouraged due to poor design
Deep copy is not always the correct choice
Shared mutable state is the root of many concurrency bugs
Copy constructors are preferred over cloning

🔹 Senior-Level Understanding
Shallow copy prioritizes performance
Deep copy prioritizes safety
Good developers know how to copy
Experienced developers know when not to copy

🔹 Final Summary
Java passes objects by reference
Shallow copy shares internal references
Deep copy isolates all state
Choosing correctly is a design decision, not a syntax decision

Understanding shallow and deep copy is not optional knowledge. It is fundamental to writing reliable,
scalable Java applications.

Interview Questions & Answers


Q 1 What is object copying in Java?

Answer:
Object copying means creating a new object using the state of an existing object. Since Java objects
are reference-based, assigning one object to another copies the reference, not the actual data.

Q 2. What is a shallow copy?

Answer:
A shallow copy creates a new object but copies only primitive fields. For reference fields, it copies the
references, so both objects point to the same nested objects.

Q 3. What is a deep copy?

Answer:
A deep copy creates a completely independent object by copying both the object and all its nested
objects. No references are shared between the original and the copied object.

Q 4. What is the main difference between shallow and deep copy?

Answer:
Shallow copy shares references of nested objects, whereas deep copy duplicates all nested objects,
ensuring complete object independence.

Q 5. Does clone() perform shallow or deep copy?

Answer:
By default, clone() performs a shallow copy. Deep copy requires explicitly cloning or recreating nested
objects.

Q 6. Why is Cloneable considered broken in Java?

Answer:
Because it:

Breaks encapsulation
Does not enforce deep copy
Is error-prone and hard to maintain
Uses a marker interface with unclear behavior

Q 7. When should you use shallow copy?

Answer:
Use shallow copy when:

Objects are immutable


Only primitive or read-only references exist
Performance is critical
Inner objects are not modified

Q 8. When should you use deep copy?

Answer:
Use deep copy when:

Objects contain mutable references


Thread safety is required
Business logic demands data isolation
Changes must not affect the original object

Q 9. Is deep copy always better than shallow copy?

Answer:
No. Deep copy is safer but consumes more memory and affects performance. The choice depends on
object complexity, mutability, and performance requirements.

Q 10. How does shallow copy affect thread safety?


Answer:
Shallow copy can be risky in multithreaded environments because shared references may lead to race
conditions and inconsistent data.

Q 11. How does deep copy improve thread safety?

Answer:
Deep copy eliminates shared mutable state by creating independent objects, making concurrent
access safer.

Q 12. How do Java collections behave during cloning?

Answer:
Most collection clone() methods perform shallow copy. The collection structure is copied, but the
elements inside are shared.

Q 13. What is the best way to implement deep copy in Java?

Answer:
Using copy constructors or factory methods is the preferred and safest approach, as it provides
explicit control over object creation.

Q 14. Can serialization be used for deep copy?

Answer:
Yes, but it is slow, memory-intensive, and not recommended for production unless simplicity is more
important than performance.

Q 15. Senior-Level Question: How do you choose between shallow and deep
copy?

Answer:
By evaluating:

Object mutability
Performance requirements
Memory constraints
Concurrency needs
Business logic impact

A senior developer chooses the copy strategy consciously, not by habit.

Author:- Krishna Makwana

You might also like