Skip to lesson

Shallow copy vs deep copy

You copy an order to make a backup, then change an item in the copy. To your surprise, the original order changes too. Why does that happen?

Objects inside objects

An object often holds other objects, as in Composition (opens in a new tab). A Student has an Address; an Order has an array of Item objects. Each such field holds a reference to the inner object, not the object itself.

So copying the outer object means a decision for every inner reference. Copy the reference, and the inner object is shared. Copy the inner object, and each side gets its own. That one choice is the whole difference between shallow and deep.

Picture 1 / 3
Step 1, the original. The variable diya points to a Student object with name Diya. Its address field holds a reference to a separate Address object whose city is Chennai.
Picture 1 / 3

Shallow copy: the inner parts are shared

A shallow copy is a new outer object whose fields are copied with =, so it holds the same references as the original and shares its inner objects and arrays. A change to an inner part through the copy shows in the original.

The hostel office fills Meera's form by copying Diya's. The Student copy constructor writes this.address = other.address;, which copies only the reference to the Address.

Example 1 · Mistake: a shallow copy shares the address

ShallowCopyDemo.javaJava
class Address {    String city;    String pin;
    Address(String city, String pin) {        this.city = city;        this.pin = pin;    }}
class Student {    String name;    Address address;
    Student(String name, Address address) {        this.name = name;        this.address = address;    }
    Student(Student other) {        this.name = other.name;        this.address = other.address;    }}
public class ShallowCopyDemo {    public static void main(String[] args) {        Student diya = new Student("Diya", new Address("Chennai", "600020"));
        Student meera = new Student(diya);        meera.name = "Meera";        meera.address.city = "Coimbatore";
        System.out.println(diya.name + " lives in " + diya.address.city);        System.out.println(meera.name + " lives in " + meera.address.city);        System.out.println("Same Student? " + (diya == meera));        System.out.println("Same Address? " + (diya.address == meera.address));    }}
Output
Diya lives in Coimbatore
Meera lives in Coimbatore
Same Student? false
Same Address? true

What this code does

  • The hostel office filled Meera's form by copying Diya's. Renaming the copy was safe: it reassigned the copy's own name field.
  • Changing meera.address.city changed the one shared Address, so Diya "moved" to Coimbatore too.

Compare the two changes. meera.name = "Meera"; reassigns the copy's own field, so it is safe. meera.address.city = ... changes the shared object, so Diya moves too. The bug is silent: diya == meera is false, and nothing looks wrong until an inner part changes.

clone() and Arrays.copyOf on an array of objects are shallow in the same way: a new array, but the same objects in its slots.

Deep copy: copy every level

A deep copy is a new outer object in which every changeable inner object and array is copied too, level by level. The copy and the original then share nothing that can change, so neither can affect the other.

Give the inner class its own copy constructor and call it from the outer one: this.address = new Address(other.address);. For an array of objects, a new array is not enough: copy each element too.

Example 2 · Fix: a deep copy gives each student an address

DeepCopyDemo.javaJava
class Address {    String city;    String pin;
    Address(String city, String pin) {        this.city = city;        this.pin = pin;    }
    Address(Address other) {        this.city = other.city;        this.pin = other.pin;    }}
class Student {    String name;    Address address;
    Student(String name, Address address) {        this.name = name;        this.address = address;    }
    Student(Student other) {        this.name = other.name;        this.address = new Address(other.address);    }}
public class DeepCopyDemo {    public static void main(String[] args) {        Student diya = new Student("Diya", new Address("Chennai", "600020"));
        Student meera = new Student(diya);        meera.name = "Meera";        meera.address.city = "Coimbatore";
        System.out.println(diya.name + " lives in " + diya.address.city);        System.out.println(meera.name + " lives in " + meera.address.city);        System.out.println("Same Address? " + (diya.address == meera.address));    }}
Output
Diya lives in Chennai
Meera lives in Coimbatore
Same Address? false

What this code does

  • Address now has its own copy constructor, and Student's copy constructor calls it: new Address(other.address).
  • Each student has a separate Address, so changing Meera's city leaves Diya in Chennai.

Example 3 · Mistake: clone() on an array of items

ReorderBugDemo.javaJava
class Item {    String name;    int qty;    int price;
    Item(String name, int qty, int price) {        this.name = name;        this.qty = qty;        this.price = price;    }
    @Override    public String toString() {        return name + " x" + qty;    }}
class Order {    String id;    Item[] items;
    Order(String id, Item[] items) {        this.id = id;        this.items = items;    }
    Order(Order other) {        this.id = other.id;        this.items = other.items.clone();    }
    int total() {        int sum = 0;        for (Item item : items) {            sum += item.qty * item.price;        }        return sum;    }
    @Override    public String toString() {        String text = id + ":";        for (int i = 0; i < items.length; i++) {            text = text + (i == 0 ? " " : ", ") + items[i];        }        return text + " = Rs " + total();    }}
public class ReorderBugDemo {    public static void main(String[] args) {        Order last = new Order("ORD-101", new Item[] {            new Item("Masala Dosa", 2, 80),            new Item("Filter Coffee", 2, 30)        });
        Order again = new Order(last);        again.id = "ORD-102";        again.items[0].qty = 3;
        System.out.println(last);        System.out.println(again);        System.out.println("Same array? " + (last.items == again.items));        System.out.println("Same first item? " + (last.items[0] == again.items[0]));    }}
Output
ORD-101: Masala Dosa x3, Filter Coffee x2 = Rs 300
ORD-102: Masala Dosa x3, Filter Coffee x2 = Rs 300
Same array? false
Same first item? true

What this code does

  • A "Reorder" button copies the last order, and the user asks for one more dosa. The old order's bill changes from Rs 220 to Rs 300.
  • clone() made a new array (Same array? false), but its slots point to the same Item objects. The copy looks separate, yet it is only one level deep.

Example 4 · Fix: deep copy each item in a loop

ReorderDeepDemo.javaJava
class Item {    String name;    int qty;    int price;
    Item(String name, int qty, int price) {        this.name = name;        this.qty = qty;        this.price = price;    }
    Item(Item other) {        this(other.name, other.qty, other.price);    }
    @Override    public String toString() {        return name + " x" + qty;    }}
class Order {    String id;    Item[] items;
    Order(String id, Item[] items) {        this.id = id;        this.items = items;    }
    Order(Order other) {        this.id = other.id;        this.items = new Item[other.items.length];        for (int i = 0; i < other.items.length; i++) {            this.items[i] = new Item(other.items[i]);        }    }
    int total() {        int sum = 0;        for (Item item : items) {            sum += item.qty * item.price;        }        return sum;    }
    @Override    public String toString() {        String text = id + ":";        for (int i = 0; i < items.length; i++) {            text = text + (i == 0 ? " " : ", ") + items[i];        }        return text + " = Rs " + total();    }}
public class ReorderDeepDemo {    public static void main(String[] args) {        Order last = new Order("ORD-101", new Item[] {            new Item("Masala Dosa", 2, 80),            new Item("Filter Coffee", 2, 30)        });
        Order again = new Order(last);        again.id = "ORD-102";        again.items[0].qty = 3;
        System.out.println(last);        System.out.println(again);        System.out.println("Same first item? " + (last.items[0] == again.items[0]));    }}
Output
ORD-101: Masala Dosa x2, Filter Coffee x2 = Rs 220
ORD-102: Masala Dosa x3, Filter Coffee x2 = Rs 300
Same first item? false

What this code does

  • The copy constructor makes a new array, then fills each slot with new Item(other.items[i]), a copy of each item.
  • Now nothing that can change is shared: the old order keeps its Rs 220 bill.

If an inner object holds objects of its own, its copy constructor copies those too. Each class copies its own level, so the deep copy works its way down. A 2D array, from Multidimensional arrays (opens in a new tab), is an array of row arrays: copy each row.

Predict the output

Deep enough?

Read the code and pick what it prints.

Round 1 of 3

A cinema copies its seat map with clone(), then books a seat in the copy.

public class Main {
public static void main(String[] args) {
int[][] seats = { {0, 0}, {0, 0} };
int[][] copy = seats.clone();
copy[0][1] = 1;
System.out.println(seats[0][1]);
}
}

When sharing is safe

A copy of Kavya's record does not need its own name or branch. A String can never change, and each enum constant, as in Enum basics (opens in a new tab), is the only object of its kind.

Example 5 · String and enum fields can be shared

SafeSharingDemo.javaJava
enum Branch { CSE, ECE, MECH }
class Student {    String name;    Branch branch;    int[] marks;
    Student(String name, Branch branch, int[] marks) {        this.name = name;        this.branch = branch;        this.marks = marks.clone();    }
    Student(Student other) {        this(other.name, other.branch, other.marks);    }}
public class SafeSharingDemo {    public static void main(String[] args) {        Student a = new Student("Kavya", Branch.CSE, new int[] {81, 77});        Student b = new Student(a);
        System.out.println("name shared:   " + (a.name == b.name));        System.out.println("branch shared: " + (a.branch == b.branch));        System.out.println("marks shared:  " + (a.marks == b.marks));
        b.name = b.name.toUpperCase();        b.branch = Branch.ECE;        b.marks[0] = 90;
        System.out.println(a.name + " " + a.branch + " " + a.marks[0]);        System.out.println(b.name + " " + b.branch + " " + b.marks[0]);    }}
Output
name shared:   true
branch shared: true
marks shared:  false
Kavya CSE 81
KAVYA ECE 90

What this code does

  • The copy shares the String and the enum constant, but gets its own marks array, the only field that can be changed in place.
  • toUpperCase() returns a new String and b.branch = Branch.ECE points b at another constant, so neither can affect a.

Copy only what can change and belongs to this object alone. String and other objects that can never change (immutable objects (opens in a new tab), next module) are safe to share. So are enum constants: new cannot create another one, and code compares them with ==. Copying them "to be safe" only wastes memory.

Deciding the copy depth

Next semester's course starts as a copy of this one. Its weekly hours belong to the course, but its teacher is one real person, shared on purpose as in Aggregation (opens in a new tab).

Example 6 · Copy what you own, share what you point to

CopyDepthDemo.javaJava
import java.util.Arrays;
class Teacher {    String name;    String phone;
    Teacher(String name, String phone) {        this.name = name;        this.phone = phone;    }}
class Course {    String code;    Teacher teacher;    int[] weeklyHours;
    Course(String code, Teacher teacher, int[] weeklyHours) {        this.code = code;        this.teacher = teacher;        this.weeklyHours = weeklyHours.clone();    }
    Course(Course other) {        this(other.code, other.teacher, other.weeklyHours);    }
    @Override    public String toString() {        return code + " by " + teacher.name + " (" + teacher.phone + ") hours " + Arrays.toString(weeklyHours);    }}
public class CopyDepthDemo {    public static void main(String[] args) {        Teacher rao = new Teacher("Prof. Rao", "98450 11111");        Course thisSem = new Course("CS201", rao, new int[] {3, 3, 4});
        Course nextSem = new Course(thisSem);        nextSem.weeklyHours[2] = 2;        rao.phone = "98450 22222";
        System.out.println(thisSem);        System.out.println(nextSem);    }}
Output
CS201 by Prof. Rao (98450 22222) hours [3, 3, 4]
CS201 by Prof. Rao (98450 22222) hours [3, 3, 2]

What this code does

  • The weekly hours belong to each course, so they are copied: cutting next semester's hours leaves this semester alone.
  • The teacher is one real person shared on purpose (aggregation), so it is not copied: one phone update reaches both courses.

Go through the fields one by one:

  • Primitive: plain = copies the value.
  • String, other immutable objects, enum constants: plain =, sharing is safe.
  • A changeable object or array that this object owns: copy it (deep).
  • An object shared on purpose, like a teacher: plain =, and say so in a comment.

For an array, decide twice: first the array itself, then its elements by the same rules.

Next step

Check your understanding

12 quick questions