You copy an object, change the copy, and the original changes too. This surprises almost every Java learner. The reason is simple. An object variable does not hold the object itself. It holds a reference, a kind of address. Many “copies” copy only that address. This lesson shows three levels of copying, from no copy at all to a full deep copy. It also looks at arrays and lists, and shows why objects that never change make the whole problem go away.
In this lesson you will learn
- The difference between a reference copy, a shallow copy and a deep copy
- How to write copy methods and copy constructors
- Why
clone()on a 2D array is only shallow - What
new ArrayList<>(list)andList.copyOfreally copy - When a shallow copy is perfectly safe
You should know classes and objects, ArrayList and immutable objects.
Three Levels of Copying
- Reference copy:
b = a. There is still one object, with two names for it. - Shallow copy: a new outer object, but its fields point to the same inner objects as before.
- Deep copy: a new outer object and new copies of every mutable object inside it.
import java.util.*;
public class Main {
static class Address {
String city;
Address(String city) { this.city = city; }
}
static 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;
}
// Shallow copy: new Student, but the SAME Address and list objects
Student shallowCopy() { return new Student(name, address, marks); }
// Deep copy: new Student AND new Address AND new list
Student deepCopy() {
return new Student(name, new Address(address.city), new ArrayList<>(marks));
}
public String toString() { return name + " " + address.city + " " + marks; }
}
public static void main(String[] args) {
Student original = new Student("Rafi", new Address("Khulna"), new ArrayList<>(List.of(80, 75)));
Student alias = original; // no copy at all
Student shallow = original.shallowCopy();
Student deep = original.deepCopy();
original.name = "Rafi Hasan"; // change a field of original
original.address.city = "Dhaka"; // change the shared Address
original.marks.add(90); // change the shared list
System.out.println("original : " + original);
System.out.println("alias : " + alias);
System.out.println("shallow : " + shallow);
System.out.println("deep : " + deep);
System.out.println("alias == original : " + (alias == original));
System.out.println("shallow.address shared? : " + (shallow.address == original.address));
System.out.println("deep.address shared? : " + (deep.address == original.address));
}
}
Output
original : Rafi Hasan Dhaka [80, 75, 90]
alias : Rafi Hasan Dhaka [80, 75, 90]
shallow : Rafi Dhaka [80, 75, 90]
deep : Rafi Khulna [80, 75]
alias == original : true
shallow.address shared? : true
deep.address shared? : false
aliasis the same object asoriginal, so it shows every change, including the new name.shallowkept the old name “Rafi”, becausenamewas copied into its own field. Strings are immutable, so the change tooriginal.namejust pointed that field at a new string.- But
shallowshares theAddressand the marks list withoriginal. So the move to Dhaka and the new mark 90 appear in both. deepmade a newAddressand a newArrayList, so it still shows Khulna and only two marks.==compares references. It tells you directly whether two variables share an object.
A good way to write a deep copy is a copy constructor, such as Student(Student other). It copies each field and makes new objects for the ones that can change. This is clearer than Java’s clone() method. That method has awkward rules, so it is best to avoid it in new code.
Copying Arrays and Lists
import java.util.*;
public class Main {
public static void main(String[] args) {
// 1. Arrays: clone() copies only the top level
int[][] grid = {{1, 2}, {3, 4}};
int[][] shallow = grid.clone();
int[][] deep = new int[grid.length][];
for (int i = 0; i < grid.length; i++) deep[i] = grid[i].clone();
grid[0][0] = 99;
System.out.println("grid : " + Arrays.deepToString(grid));
System.out.println("shallow : " + Arrays.deepToString(shallow));
System.out.println("deep : " + Arrays.deepToString(deep));
// 2. Copying collections
List<StringBuilder> names = new ArrayList<>(List.of(new StringBuilder("Mim"), new StringBuilder("Tuli")));
List<StringBuilder> copy = new ArrayList<>(names); // new list, same elements
List<StringBuilder> frozen = List.copyOf(names); // unmodifiable, same elements
copy.add(new StringBuilder("Joy")); // only the copy grows
names.get(0).append(" Akter"); // element is shared by all three
System.out.println("names : " + names);
System.out.println("copy : " + copy);
System.out.println("frozen : " + frozen);
try {
frozen.add(new StringBuilder("X"));
} catch (UnsupportedOperationException e) {
System.out.println("frozen.add -> UnsupportedOperationException");
}
// 3. Immutable elements make shallow copies safe
List<String> cities = new ArrayList<>(List.of("Sylhet", "Rajshahi"));
List<String> citiesCopy = new ArrayList<>(cities);
cities.set(0, "Barishal");
System.out.println("cities : " + cities);
System.out.println("citiesCopy : " + citiesCopy);
}
}
Output
grid : [[99, 2], [3, 4]]
shallow : [[99, 2], [3, 4]]
deep : [[1, 2], [3, 4]]
names : [Mim Akter, Tuli]
copy : [Mim Akter, Tuli, Joy]
frozen : [Mim Akter, Tuli]
frozen.add -> UnsupportedOperationException
cities : [Barishal, Rajshahi]
citiesCopy : [Sylhet, Rajshahi]
- A 2D array is an array of row arrays.
grid.clone()makes a new outer array, but the rows are shared, so changinggrid[0][0]also changesshallow. Cloning each row gives a true deep copy. new ArrayList<>(names)makes a new list. Adding tocopydoes not touchnames.- But the elements are shared.
StringBuilderis mutable, so appending ” Akter” to the first one shows up in all three lists. List.copyOfgives a list that cannot be changed: adding to it throwsUnsupportedOperationException. Its elements are still shared, though.- When the elements are immutable, like
String, a shallow copy is all you need.cities.set(0, ...)replaces an element in one list only.
| Code | New container? | New elements? |
|---|---|---|
b = a | No | No |
arr.clone(), Arrays.copyOf | Yes | No |
new ArrayList<>(list) | Yes | No |
List.copyOf(list) | Yes, unmodifiable | No |
| Loop that copies each element | Yes | Yes (deep) |
Common Mistakes
- Thinking
b = acopies an object. It copies the reference only. - Returning an internal list from a getter. Callers can then change your object’s data. Return
List.copyOf(marks)instead. - Using
clone()on a 2D array and expecting independent rows. - Deep-copying immutable objects. It wastes memory and time; sharing a
Stringor arecordof immutable fields is safe. - Forgetting that an unmodifiable list can still hold mutable elements.
Practice Exercises
Exercise 1. Write a copy constructor for Student from the first program.
Show answer
Student(Student other) {
this(other.name,
new Address(other.address.city),
new ArrayList<>(other.marks));
}
The name is a String, so it is safe to share. The address and the list can change, so we make new ones.
Exercise 2. After this code, what does a[0] hold?
int[] a = {1, 2, 3};
int[] b = a.clone();
b[0] = 50;
Show answer
a[0] is still 1. An array of int holds plain numbers, not references. So clone() makes a fully separate copy.
Frequently Asked Questions
What is the difference between shallow copy and deep copy in Java?
A shallow copy makes a new object, but the fields inside still point to the same inner objects. A deep copy also makes new copies of the inner objects that can change. Then a change to one copy never shows up in the other.
Should I use clone() in Java?
For arrays, clone() is fine and simple. For your own classes, use a copy constructor or a static copy method. The rules for Cloneable and Object.clone are confusing, and by default they only give a shallow copy.
Summary
- Object variables hold references;
=copies the reference. - A shallow copy shares inner objects; a deep copy makes new ones.
clone(),Arrays.copyOf,new ArrayList<>(...)andList.copyOfare all shallow.- Write copy constructors for your own deep copies.
- Immutable elements can be shared safely, so a shallow copy is enough.
