Chapter 17 of 26

Shallow Copy vs Deep Copy

Suppose you photocopy a notebook. You get new pages with the same writing. But imagine one page just says "see the drawing in the blue folder". Your copy also says "see the drawing in the blue folder", and both notebooks now point to the same folder. If someone scribbles on that drawing, both notebooks are affected.

That is exactly the difference between a shallow copy and a deep copy. In the Object Lifecycle & Memory chapter we saw that a variable holding an object really holds a reference. Objects often contain references to other objects too, and copying an object raises the question: do we copy those inner objects, or only the references to them?

A shallow copy creates a new object and copies each field's value as-is; for reference fields this means the copy and the original share the same inner objects.

A deep copy creates a new object and also recursively copies every mutable object it refers to, so the copy and the original share no mutable state.


Step 0: Assignment Is Not a Copy

Before talking about copies at all, remember that = on a reference variable copies the reference, not the object.

public class ReferenceCopy {
    public static void main(String[] args) {
        int x = 10;
        int y = x;          // copies the VALUE 10
        y = 99;
        System.out.println("x = " + x);

        int[] first = {1, 2, 3};
        int[] second = first;   // copies the REFERENCE, not the array
        second[0] = 99;
        System.out.println("first[0] = " + first[0]);
        System.out.println("same object? " + (first == second));
    }
}

Output:

x = 10
first[0] = 99
same object? true

For the primitive, y got its own value. For the array, second is just a second name for the same array. This is sometimes called aliasing. So there are really three levels:

 Reference copy (alias)      Shallow copy                    Deep copy
 ─────────────────────       ──────────────────              ──────────────────
 a ──┐                       a ──▶ [obj] ──┐                 a ──▶ [obj] ──▶ [inner]
     ├──▶ [obj] ──▶ [inner]                ├──▶ [inner]
 b ──┘                       b ──▶ [obj'] ─┘                 b ──▶ [obj'] ──▶ [inner']

 one object                  two outer objects,              everything
                             shared inner objects            duplicated

Shallow vs Deep Copy in Java: A Full Example

Our Student has four kinds of fields, and each behaves differently when copied:

  • int rollNo: a primitive. Always copied by value.

  • String name: a reference, but to an immutable object. Sharing is harmless because nobody can change it.

  • int[] marks: a reference to a mutable array.

  • Address address: a reference to a mutable object.

We make a shallow copy with Object.clone() and a deep copy by hand.

import java.util.Arrays;

public class CopyDemo {

    static class Address {
        String city;

        Address(String city) { this.city = city; }

        Address(Address other) { this.city = other.city; }   // copy constructor
    }

    static class Student implements Cloneable {
        String name;        // String is immutable: sharing it is safe
        int rollNo;         // primitive: always copied by value
        int[] marks;        // mutable array: sharing it is dangerous
        Address address;    // mutable object: sharing it is dangerous

        Student(String name, int rollNo, int[] marks, Address address) {
            this.name = name;
            this.rollNo = rollNo;
            this.marks = marks;
            this.address = address;
        }

        // SHALLOW copy: Object.clone() copies each field as-is
        Student shallowCopy() {
            try {
                return (Student) super.clone();
            } catch (CloneNotSupportedException e) {
                throw new AssertionError(e);   // cannot happen: we implement Cloneable
            }
        }

        // DEEP copy: also copy every mutable object the fields point to
        Student deepCopy() {
            return new Student(name, rollNo, marks.clone(), new Address(address));
        }

        @Override
        public String toString() {
            return name + " " + rollNo + " " + Arrays.toString(marks) + " " + address.city;
        }
    }

    public static void main(String[] args) {
        Student original = new Student("Asha", 1, new int[]{80, 90}, new Address("Pune"));

        Student shallow = original.shallowCopy();
        Student deep = original.deepCopy();

        // Change the original's nested data
        original.rollNo = 7;
        original.marks[0] = 10;
        original.address.city = "Delhi";

        System.out.println("original: " + original);
        System.out.println("shallow : " + shallow);
        System.out.println("deep    : " + deep);

        System.out.println("shallow shares marks?   " + (shallow.marks == original.marks));
        System.out.println("shallow shares address? " + (shallow.address == original.address));
        System.out.println("deep shares address?    " + (deep.address == original.address));
    }
}

Output:

original: Asha 7 [10, 90] Delhi
shallow : Asha 1 [10, 90] Delhi
deep    : Asha 1 [80, 90] Pune
shallow shares marks?   true
shallow shares address? true
deep shares address?    false

Let us read the result carefully:

Change made to original

Visible in shallow copy?

Visible in deep copy?

Why

rollNo = 7

No

No

Primitive field: each object has its own value

marks[0] = 10

Yes

No

Shallow copy shares the same array

address.city = "Delhi"

Yes

No

Shallow copy shares the same Address object

The shallow copy looked independent at first, but it was secretly connected to the original through its reference fields. This is the source of many confusing bugs: you change one object and a "different" object changes too.

How Object.clone() Works

  • clone() is a protected method of Object. It creates a new object of the same class and copies every field bit for bit. That is a shallow copy.

  • The class must implement the marker interface Cloneable; otherwise Object.clone() throws CloneNotSupportedException.

  • No constructor is called for the clone.

  • To make a deep copy with clone(), you must override it and clone each mutable field yourself.

Many experienced Java developers (including Joshua Bloch in Effective Java) recommend avoiding Cloneable in new code because it is easy to get wrong: it bypasses constructors, does not work well with final fields that need new values, and forces you to deal with a checked exception. The preferred alternatives are a copy constructor (new Address(other), as above) or a static copy factory (Address.copyOf(other)).


Arrays and Collections Are Shallow Too

The built-in copying tools in Java are almost all shallow. This catches many students in coding rounds.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayAndListCopy {
    public static void main(String[] args) {
        // 1. clone() of a 1-D int array: elements are primitives, so it acts deep
        int[] a = {1, 2, 3};
        int[] b = a.clone();
        b[0] = 100;
        System.out.println("a = " + Arrays.toString(a));

        // 2. clone() of a 2-D array copies only the outer array
        int[][] grid = {{1, 2}, {3, 4}};
        int[][] gridCopy = grid.clone();
        gridCopy[0][0] = 100;
        System.out.println("grid = " + Arrays.deepToString(grid));

        // Deep copy of a 2-D array: clone every row
        int[][] gridDeep = new int[grid.length][];
        for (int i = 0; i < grid.length; i++) {
            gridDeep[i] = grid[i].clone();
        }
        gridDeep[1][1] = -1;
        System.out.println("grid = " + Arrays.deepToString(grid));

        // 3. new ArrayList<>(list) copies the list, not the elements
        List<StringBuilder> names = new ArrayList<>();
        names.add(new StringBuilder("Ravi"));
        List<StringBuilder> namesCopy = new ArrayList<>(names);
        namesCopy.add(new StringBuilder("Meera"));       // list structure is separate
        namesCopy.get(0).append(" Kumar");               // element is shared
        System.out.println("names = " + names);
        System.out.println("namesCopy = " + namesCopy);
    }
}

Output:

a = [1, 2, 3]
grid = [[100, 2], [3, 4]]
grid = [[100, 2], [3, 4]]
names = [Ravi Kumar]
namesCopy = [Ravi Kumar, Meera]
  1. For int[], clone() is shallow too, but the elements are primitives, so the result is effectively a full independent copy.

  2. A 2-D array is an array of references to row arrays. grid.clone() copies only the outer array, so gridCopy[0] and grid[0] are the same row. Changing gridCopy[0][0] changed grid.

  3. Cloning every row gives a real deep copy: changing gridDeep[1][1] left grid untouched (the second print is the same as the first).

  4. new ArrayList<>(list) creates a new list (adding to it does not affect the old one), but both lists hold the same element objects.

Java tool

Kind of copy

b = a

Reference only (alias)

array.clone(), Arrays.copyOf, System.arraycopy

Shallow

new ArrayList<>(c), List.copyOf(c), new HashMap<>(m)

Shallow

Object.clone() (default)

Shallow

Copy constructor / overridden clone() that copies mutable fields

Deep (if you write it that way)

Serialize and deserialize

Deep, but slow and requires Serializable


When Is a Shallow Copy Enough?

Deep copies cost time and memory, so you should not always deep copy. A useful rule:

You only need to deep copy the parts of an object that are mutable and that you do not want to share.

  • Immutable objects (String, Integer, LocalDate, records whose fields are themselves immutable) can be shared safely, so a shallow copy is effectively deep.

  • Sometimes sharing is intended. Two Order objects can both refer to the same Customer; copying the customer would actually be wrong. This matches the aggregation idea from the Association, Aggregation & Composition chapter: in a composition (the part belongs only to the whole), a copy of the whole should get its own parts; in an aggregation, sharing the part is usually correct.

  • Deep copies of large object graphs can be expensive, and graphs with cycles need extra care so that you do not copy forever.


Defensive Copying

Copying is also an encapsulation tool. If a class stores a mutable object passed in by a caller, the caller still holds a reference to it and can change your object's internal state from outside. The fix is a defensive copy: copy on the way in, and do not hand out your internal mutable objects on the way out.

import java.util.ArrayList;
import java.util.List;

public class DefensiveCopy {

    static final class Course {
        private final String title;
        private final List<String> students;

        Course(String title, List<String> students) {
            this.title = title;
            this.students = List.copyOf(students);   // copy IN (and make it unmodifiable)
        }

        List<String> getStudents() {
            return students;   // safe to return: callers cannot modify it
        }

        @Override
        public String toString() {
            return title + " " + students;
        }
    }

    public static void main(String[] args) {
        List<String> input = new ArrayList<>(List.of("Asha", "Ravi"));
        Course course = new Course("OOP", input);

        input.add("Hacker");                      // caller changes its own list later
        System.out.println(course);

        try {
            course.getStudents().add("Hacker");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify: " + e.getClass().getSimpleName());
        }
    }
}

Output:

OOP [Asha, Ravi]
Cannot modify: UnsupportedOperationException

List.copyOf makes a shallow, unmodifiable copy. The list is independent of the caller's list, and because its elements are immutable Strings, the Course is fully protected. If the elements were mutable, you would need to copy them too.


C++: The Compiler-Generated Copy Is Shallow for Pointers

In C++, copying an object of class type calls its copy constructor. If you do not write one, the compiler generates a memberwise copy: each member is copied using its own copy operation. For a raw pointer member, that copies the address, which is a shallow copy.

#include <iostream>

// A class that owns a heap array through a raw pointer
class Buffer {
public:
    int size;
    int* data;

    explicit Buffer(int n) : size(n), data(new int[n]{}) {}
    // No copy constructor written: the compiler generates a memberwise one,
    // which copies the POINTER, not the array it points to.
};

int main() {
    Buffer a(3);
    Buffer b = a;          // compiler-generated copy: shallow

    b.data[0] = 42;
    std::cout << "a.data[0] = " << a.data[0] << '\n';
    std::cout << "same array? " << std::boolalpha << (a.data == b.data) << '\n';

    delete[] a.data;       // free once; b.data now dangles
    // delete[] b.data;    // would free the same memory twice: undefined behaviour
}

Output:

a.data[0] = 42
same array? true

This is more dangerous than in Java. If Buffer had a destructor that did delete[] data, then both a and b would free the same array when they go out of scope. That double delete is undefined behavior and often crashes the program.

The Fix: Rule of Three (and Rule of Zero)

Rule of three: if a class needs a user-defined destructor, copy constructor or copy assignment operator, it almost certainly needs all three. Since C++11 the rule of five adds the move constructor and move assignment operator.

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

// Rule of three: a class that owns a raw resource needs a destructor,
// copy constructor and copy assignment operator that all agree.
class Buffer {
    int size;
    int* data;
public:
    explicit Buffer(int n) : size(n), data(new int[n]{}) {}

    ~Buffer() { delete[] data; }

    Buffer(const Buffer& other)                    // deep copy constructor
        : size(other.size), data(new int[other.size]) {
        std::copy(other.data, other.data + size, data);
        std::cout << "deep copy made\n";
    }

    Buffer& operator=(Buffer other) {              // copy-and-swap assignment
        std::swap(size, other.size);
        std::swap(data, other.data);
        return *this;                              // old data freed with 'other'
    }

    int& operator[](int i) { return data[i]; }
    const int* raw() const { return data; }
};

// Rule of zero: let a standard container own the memory instead.
struct SafeBuffer {
    std::vector<int> data;
};

int main() {
    Buffer a(3);
    Buffer b = a;              // calls the deep copy constructor
    b[0] = 42;
    std::cout << "a[0] = " << a[0] << ", b[0] = " << b[0] << '\n';
    std::cout << "same array? " << std::boolalpha << (a.raw() == b.raw()) << '\n';

    Buffer c(1);
    c = a;                     // copy assignment also deep-copies
    c[1] = 7;
    std::cout << "a[1] = " << a[1] << ", c[1] = " << c[1] << '\n';

    SafeBuffer s1{{1, 2, 3}};
    SafeBuffer s2 = s1;        // vector's copy constructor copies the elements
    s2.data[0] = 99;
    std::cout << "s1.data[0] = " << s1.data[0] << '\n';
}   // every destructor frees its own array exactly once

Compiled with g++ -std=c++23 -fsanitize=address (AddressSanitizer reported no errors). Output:

deep copy made
a[0] = 0, b[0] = 42
same array? false
deep copy made
a[1] = 0, c[1] = 7
s1.data[0] = 1
  • The copy constructor allocates a new array and copies the elements: a deep copy.

  • The assignment operator uses the copy-and-swap idiom: the parameter is taken by value (which makes a deep copy), then swapped in. The old array is freed when the parameter is destroyed. It is also safe for self-assignment.

  • SafeBuffer follows the rule of zero: it holds a std::vector, which already knows how to deep copy, move and free itself, so the class needs no special member functions at all. This is the preferred style in modern C++.


Python: copy.copy() and copy.deepcopy()

Python's standard copy module gives both kinds of copy for any object.

import copy

original = {"name": "Asha", "marks": [80, 90], "address": {"city": "Pune"}}

alias = original                 # no copy at all: same object
shallow = copy.copy(original)    # new dict, same inner list and dict
deep = copy.deepcopy(original)   # new dict, new list, new inner dict

original["name"] = "Asha K"      # rebinding a key: only affects original
original["marks"][0] = 10        # mutating a shared inner object
original["address"]["city"] = "Delhi"

print("alias  :", alias)
print("shallow:", shallow)
print("deep   :", deep)
print("shallow marks is original marks?", shallow["marks"] is original["marks"])
print("deep marks is original marks?   ", deep["marks"] is original["marks"])

# The classic list-of-lists trap
grid = [[0] * 3] * 2             # two references to ONE inner list
grid[0][0] = 5
print("grid:", grid)
grid = [[0] * 3 for _ in range(2)]   # two separate inner lists
grid[0][0] = 5
print("grid:", grid)

Output:

alias  : {'name': 'Asha K', 'marks': [10, 90], 'address': {'city': 'Delhi'}}
shallow: {'name': 'Asha', 'marks': [10, 90], 'address': {'city': 'Delhi'}}
deep   : {'name': 'Asha', 'marks': [80, 90], 'address': {'city': 'Pune'}}
shallow marks is original marks? True
deep marks is original marks?    False
grid: [[5, 0, 0], [5, 0, 0]]
grid: [[5, 0, 0], [0, 0, 0]]

The pattern is identical to Java: the shallow copy has its own top-level keys (so renaming did not leak through) but shares the inner list and dict. deepcopy also keeps a memo of objects already copied, so it handles cycles and shared references correctly. The last two lines show the famous [[0] * 3] * 2 trap: * repeats the reference to one inner list.


Comparison Summary

Feature

Shallow copy

Deep copy

Top-level object

New

New

Primitive fields

Copied

Copied

Referenced objects

Shared

Recursively copied

Speed and memory

Fast, cheap

Slower, uses more memory

Independence

Partial: changes to inner objects are visible in both

Full

Java

Default clone(), collection copy constructors

Copy constructor that copies mutable fields

C++

Compiler-generated copy with raw pointers

User-defined copy constructor, or containers (rule of zero)

Python

copy.copy(), list(x), x[:], dict.copy()

copy.deepcopy()


Common Mistakes

  • Thinking b = a makes a copy. For objects it only creates a second reference.

  • Assuming clone() is deep. Object.clone() and array clone() are shallow.

  • Cloning a 2-D array with one clone() call. Clone each row as well.

  • Copying a list and assuming the elements are copied. new ArrayList<>(list) shares elements.

  • Writing a destructor in C++ but no copy constructor. The default shallow copy then causes double deletes. Follow the rule of three/five, or better, the rule of zero.

  • Deep copying everything "just to be safe". Immutable objects and intentionally shared objects do not need copying.


Interview Questions

What is the difference between shallow copy and deep copy?

A shallow copy creates a new object but copies reference fields as references, so inner objects are shared. A deep copy also copies the inner mutable objects recursively, so the copy is completely independent.

Is Object.clone() shallow or deep? What is required to use it?

Shallow: it copies field values bit for bit. The class must implement Cloneable (otherwise CloneNotSupportedException is thrown), and usually overrides clone() as public. For a deep copy, the override must clone mutable fields itself.

Why might you prefer a copy constructor over clone() in Java?

A copy constructor is ordinary code: it runs constructors, works with final fields, needs no casts or checked exceptions, and makes it obvious which fields are deep-copied. Cloneable has an awkward, error-prone contract.

int[][] b = a.clone(); b[0][0] = 5; Does a change?

Yes. clone() copies only the outer array of row references, so b[0] and a[0] are the same row array.

What is the rule of three in C++?

If a class needs a user-defined destructor, copy constructor or copy assignment operator, it almost always needs all three, because it is managing a resource. With move semantics this becomes the rule of five. The rule of zero says: prefer members like std::vector and smart pointers so you need none of them.

When is a shallow copy sufficient?

When all referenced objects are immutable, or when sharing them is the intended design (for example, many orders referring to the same customer).


Summary

  • Assignment of a reference creates an alias, not a copy.

  • A shallow copy duplicates the outer object but shares inner objects.

  • A deep copy duplicates inner mutable objects too, giving full independence.

  • Java's clone(), array copies and collection copies are shallow; prefer copy constructors for deep copies.

  • Immutable objects never need deep copying; defensive copies protect encapsulation.

  • In C++, follow the rule of three/five for raw resources, or the rule of zero with standard containers. In Python, use copy.copy() and copy.deepcopy().

So far we have studied how individual classes and objects work. From the next chapter we start learning the principles that tell us how to design classes well, beginning with SOLID: Single Responsibility & Open/Closed.