← Back to Questions
Java

Difference between shallow copy and deep copy in Java?

Learn Difference between shallow copy and deep copy in Java? with simple explanations, real-time examples, interview tips and practical use cases.

Difference Between Shallow Copy and Deep Copy in Java

In Java, copying objects can be done in two ways:

  • Shallow Copy
  • Deep Copy

Both are used in object cloning and object duplication.

In simple words:

Shallow copy shares referenced objects, while deep copy creates completely independent copies.


Why Understanding Copy Types is Important?

Understanding shallow and deep copy helps:

  • Avoid accidental data modification
  • Prevent memory-sharing issues
  • Build safe enterprise applications
  • Handle object cloning correctly
  • Improve application reliability

Overview Diagram


Object Copying

     |
     +-------> Shallow Copy

     |
     +-------> Deep Copy


What is Shallow Copy?

In shallow copy:

  • Primitive values are copied
  • Object references are shared

Shallow Copy Diagram


Original Object

     |
     +-------> Shared Address Object

     |
     v

Copied Object


Shallow Copy Example

class Address {

    String city;

    Address(String city) {

        this.city = city;

    }

}

class Employee
implements Cloneable {

    int id;
    Address address;

    Employee(int id, Address address) {

        this.id = id;
        this.address = address;

    }

    public Object clone()
    throws CloneNotSupportedException {

        return super.clone();

    }

}

Using Shallow Copy

Address a1 =
    new Address("Hyderabad");

Employee e1 =
    new Employee(101, a1);

Employee e2 =
    (Employee) e1.clone();

Memory Representation


e1 --------------+

                 |

                 v

            Address Object

                 ^

                 |

e2 --------------+


Problem with Shallow Copy

Both objects share the same referenced object.


Example

e2.address.city = "Bangalore";

Result

Both e1 and e2 now show:

Bangalore

Why?

Because both objects point to same Address object.


What is Deep Copy?

In deep copy:

  • Primitive values are copied
  • Referenced objects are also copied

Deep Copy Diagram


Original Object

      |
      +-------> Separate Address Object

      |
      v

Copied Object


Deep Copy Example

class Address
implements Cloneable {

    String city;

    Address(String city) {

        this.city = city;

    }

    public Object clone()
    throws CloneNotSupportedException {

        return super.clone();

    }

}

class Employee
implements Cloneable {

    int id;
    Address address;

    Employee(int id, Address address) {

        this.id = id;
        this.address = address;

    }

    public Object clone()
    throws CloneNotSupportedException {

        Employee emp =
            (Employee) super.clone();

        emp.address =
            (Address) address.clone();

        return emp;

    }

}

Memory Representation


e1 ---------> Address Object 1


e2 ---------> Address Object 2


Now What Happens?

e2.address.city = "Bangalore";

Result

  • e1 remains unchanged
  • e2 changes independently

Why Deep Copy is Safer?

Because copied objects become fully independent.


Shallow Copy vs Deep Copy

Feature Shallow Copy Deep Copy
Primitive Values Copied Copied
Object References Shared Copied Separately
Memory Usage Less More
Performance Faster Slightly Slower
Safety Lower Higher
Object Independence No Yes

Internal Working of Shallow Copy


Original Object

      |
      v

Field Values Copied

      |
      v

References Shared


Internal Working of Deep Copy


Original Object

      |
      v

Field Values Copied

      |
      v

Nested Objects Also Copied


Why Shallow Copy is Faster?

Because only references are copied, not entire nested objects.


Why Deep Copy Uses More Memory?

Because entirely new object hierarchy is created.


Real-Time Banking Example

Shallow Copy Problem

Suppose transaction history is shared accidentally:


Account A ----+

              |

              v

        Shared Transaction List

              ^

              |

Account B ----+

Modification in one account affects another.


Deep Copy Solution

Each account gets independent transaction history.


Real-Time E-Commerce Example

Shallow Copy

Shared shopping cart objects may cause:

  • Duplicate order issues
  • Unexpected inventory updates

Deep Copy

Each order gets independent product snapshot.


Shallow Copy in Spring Boot

Spring Boot applications may use shallow copy for:

  • DTO transfers
  • Read-only shared objects
  • Performance optimization

Deep Copy in Spring Boot

Spring Boot applications use deep copy for:

  • Immutable snapshots
  • Secure transaction states
  • Rollback systems
  • Distributed caching

Alternative Ways for Deep Copy

  • Copy constructors
  • Serialization
  • Builder pattern
  • Manual object copying

Copy Constructor Example

class Employee {

    int id;

    Address address;

    Employee(Employee e) {

        this.id = e.id;

        this.address =
            new Address(
                e.address.city
            );

    }

}

Serialization-Based Deep Copy

Serialization can create deep copies automatically.


Serialization Flow


Object Serialized

      |
      v

Byte Stream Created

      |
      v

Deserialized into New Object


Object Cloning Relationship

By default:

  • clone() performs shallow copy.

Why?

super.clone() copies object fields directly.


Deep Copy Requires Manual Logic

Nested objects must be cloned separately.


Shallow Copy Memory Flow


Original Object

      |
      +-------> Shared Nested Objects

      |
      v

Copied Object


Deep Copy Memory Flow


Original Object

      |
      +-------> Independent Nested Objects

      |
      v

Copied Object


Advantages of Shallow Copy

  • Fast execution
  • Less memory usage
  • Simple implementation

Disadvantages of Shallow Copy

  • Shared references cause side effects
  • Unsafe for mutable objects
  • Difficult debugging sometimes

Advantages of Deep Copy

  • Independent objects
  • Safer modifications
  • Better enterprise reliability
  • No shared state problems

Disadvantages of Deep Copy

  • Higher memory usage
  • More processing time
  • Complex implementation

Common Interview Mistake

Many developers think clone() automatically performs deep copy.

Actually:

  • Default clone() creates shallow copy.

Another Common Mistake

Many developers think deep copy is always better.

Actually:

  • Deep copy increases memory and CPU usage.
  • Choose based on use case.

Best Practices

  • Use deep copy for mutable shared objects
  • Use shallow copy for immutable/read-only objects
  • Prefer copy constructors for readability
  • Be careful with nested references

Microservices Usage

Microservices architectures use:

  • Shallow copy → Lightweight DTO sharing
  • Deep copy → Transaction snapshots and rollback systems

Realtime Enterprise Example

Order Processing

Order backupOrder =
    deepCopy(currentOrder);

Used before payment confirmation to support rollback.


Related Learning Topics


Professional Interview Answer

In Java, shallow copy copies primitive values while sharing object references, whereas deep copy creates completely independent copies of both primitive values and referenced objects. By default, the clone() method performs shallow copying because it copies field values directly without cloning nested objects. Deep copy is safer for enterprise applications because changes in cloned objects do not affect original objects. Shallow copy is faster and memory efficient, while deep copy provides better isolation and reliability. Enterprise systems, banking applications, Spring Boot services, and microservices architectures commonly use deep copying for transaction snapshots, rollback systems, and immutable state management.


Frequently Asked Questions

What is shallow copy in Java?

Shallow copy copies primitive values but shares object references.

What is deep copy in Java?

Deep copy creates completely independent copies including nested objects.

Does clone() perform deep copy by default?

No, clone() performs shallow copy by default.

Which copy is safer?

Deep copy is safer because objects are independent.

Why is deep copy slower?

Because entire object hierarchy must be duplicated.

Why this Java question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.