Skills101

AdvancedOOP Concepts · Lesson 15 of 16 · Updated ·

Shallow Copy vs Deep Copy in Java — Assignment, clone() and Copy Constructors

"What is the difference between a shallow copy and a deep copy?" is a standard Java interview question. It also explains a very common bug: you make a "copy" of an object, change the copy, and the original changes too. To understand why, you need one idea — a variable of a class type holds a reference (an address), not the object itself.

1. Assignment copies the reference, not the object

class Student {
    String name;
    int marks;
    Student(String name, int marks) { this.name = name; this.marks = marks; }
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student("Asha", 80);
        Student b = a;              // no new object is created
        b.marks = 95;
        System.out.println(a.marks + " " + (a == b));
    }
}
95 true

b = a copies the reference. Both names point to the same Student object on the heap, so a change through b is visible through a. a == b is true because == on objects compares references.

There are three levels of "copying":

WayNew outer object?Inner objects (fields that are objects)
Assignment b = aNoShared
Shallow copyYesShared — only the references are copied
Deep copyYesCopied too, all the way down

Three panels: with assignment a and b point to one Student; with a shallow copy there are two Students sharing one Address; with a deep copy each Student has its own Address

2. Shallow copy with clone()

Java has a built-in copy mechanism: Object.clone(). To use it, a class implements the marker interface Cloneable (an interface with no methods; it only "marks" the class as allowed to be cloned) and overrides clone(). Calling super.clone() creates a new object and copies every field value as it is. For a field that holds a reference, the reference is copied — so the copy is shallow.

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

class Student implements Cloneable {
    String name;
    Address address;
    Student(String name, Address address) { this.name = name; this.address = address; }

    @Override
    public Student clone() {
        try {
            return (Student) super.clone();       // field-by-field copy
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(e);          // cannot happen: we implement Cloneable
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student("Asha", new Address("Jaipur"));
        Student b = a.clone();
        b.name = "Ravi";                 // re-points b's own field
        b.address.city = "Pune";         // changes the SHARED Address object
        System.out.println(a.name + " lives in " + a.address.city);
        System.out.println((a == b) + " " + (a.address == b.address));
    }
}
Asha lives in Pune
false true

Read the output carefully:

  • a.name is still Asha. b.name = "Ravi" changed which string b's own field points to. It did not change any shared object.
  • a.address.city became Pune. b.address.city = "Pune" changed the Address object, and both students point to the same Address.
  • a == b is false (two Student objects), but a.address == b.address is true (one Address object).

So a shallow copy is safe only when the shared inner objects are immutable (like String, Integer, LocalDate) or are never changed.

3. Deep copy with a copy constructor

A deep copy also copies every mutable object inside. The clearest way to write one is a copy constructor — a constructor that takes another object of the same class and copies it.

import java.util.*;

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

class Student {
    String name;
    Address address;
    List<Integer> marks;

    Student(String name, Address address, List<Integer> marks) {
        this.name = name;
        this.address = address;
        this.marks = marks;
    }

    Student(Student other) {                                 // deep copy
        this.name = other.name;                              // String is immutable: sharing is fine
        this.address = new Address(other.address);           // new Address
        this.marks = new ArrayList<>(other.marks);           // new list (Integers are immutable)
    }
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student("Asha", new Address("Jaipur"), new ArrayList<>(List.of(70, 80)));
        Student b = new Student(a);
        b.address.city = "Pune";
        b.marks.add(90);
        System.out.println(a.address.city + " " + a.marks);
        System.out.println(b.address.city + " " + b.marks);
    }
}
Jaipur [70, 80]
Pune [70, 80, 90]

Now the two students are fully independent. Notice the decision made for each field:

  • String name — immutable, so copying the reference is enough.
  • Address — mutable, so we create a new one (using its copy constructor).
  • List<Integer> — the list is mutable, so we create a new list. The Integer elements inside are immutable, so they can be shared.

If the list held mutable objects (say, List<Address>), a real deep copy would also have to copy each element.

4. The array trap: clone() on a 2D array

Arrays have a public clone() method. For a 1D array of primitives it gives an independent copy. But a 2D array in Java is an array of arrays — the outer array holds references to row arrays. clone() copies only the outer array, so the rows are shared.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {70, 80, 90};
        int[] copy = marks.clone();
        copy[0] = 99;
        System.out.println(Arrays.toString(marks));

        int[][] grid = {{1, 2}, {3, 4}};
        int[][] shallow = grid.clone();
        shallow[0][0] = 99;
        System.out.println(Arrays.deepToString(grid));

        int[][] deep = new int[grid.length][];
        for (int i = 0; i < grid.length; i++) deep[i] = grid[i].clone();   // clone each row
        deep[1][1] = 0;
        System.out.println(Arrays.deepToString(grid));
    }
}
[70, 80, 90]
[[99, 2], [3, 4]]
[[99, 2], [3, 4]]

The 1D copy is independent, so marks is unchanged. The 2D clone() is shallow, so grid[0][0] became 99. Cloning each row gives a deep copy, so deep[1][1] = 0 does not touch grid.

A 2D array clone: the outer arrays of grid and its clone are different, but both point to the same two row arrays, so copy[0][0] = 99 also changes grid[0][0]

5. clone() or copy constructor?

clone() looks convenient, but it has well-known design problems, which is why many Java style guides (including the book Effective Java) recommend copy constructors or copy factory methods instead:

Problem with clone()Why it hurts
Cloneable has no methodsThe interface does not promise a public clone(); the method lives in Object and is protected
Shallow by defaultYou must remember to copy every mutable field by hand anyway
Skips constructorsValidation in the constructor does not run for the copy
Fights with final fieldsYou cannot assign a new deep copy to a final field after super.clone()
Checked exception and castCloneNotSupportedException and (Student) clutter every call

A copy constructor (or a static method such as Student.copyOf(other)) is plain Java: it runs your validation, works with final fields, and makes every copying decision visible.

The best option of all is often no copy at all: if a class is immutable (see the lesson on immutable classes and value objects), sharing it is always safe.

Common mistakes

  • Thinking Student b = a; makes a copy. It only makes a second reference to the same object.
  • Calling clone() and assuming the nested objects (lists, addresses, arrays) are copied too.
  • Using grid.clone() on a 2D array and expecting independent rows.
  • Forgetting implements Cloneable: super.clone() then throws CloneNotSupportedException at runtime.
  • Deep-copying immutable fields such as String — it wastes memory and adds nothing.
  • In a deep copy of a List of mutable objects, copying the list but not the objects inside it.

Quick recap

  • A variable of a class type holds a reference. Assignment copies the reference.
  • Shallow copy: a new outer object whose fields point to the same inner objects.
  • Deep copy: the outer object and every mutable object inside are copied.
  • Object.clone() with Cloneable gives a shallow copy; arrays' clone() is shallow for 2D arrays.
  • Prefer copy constructors or copy factories; prefer immutable objects, which never need copying.

Practice what you learned

📝 Quiz: Shallow and Deep Copy5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →