Member-only story
Java Shallow Copy vs Deep Copy with Examples
In this article, we’ll explain what shallow and deep copies are, when to use them, how they work internally, and how to implement each in Java.
🔒 This is a Medium member-only article. You can read it for free on my blog: Shallow Copy vs Deep Copy in Java.
In Java, when you clone or copy an object, you may expect the new object to be completely independent of the original one. But that’s not always the case. Depending on how you copy an object, changes in one can affect the other — or not.
This brings us to two important concepts in Java object copying: Shallow Copy and Deep Copy. Although they sound similar, their behavior is very different.
📘 What is Shallow Copy?
A shallow copy is a copy of an object where:
- The new object has copies of primitive fields.
- The references to objects inside it are shared between the original and the cloned object.
This means the cloned and original objects are not 100% independent — they share inner objects.
✅ Characteristics of Shallow Copy
Shallow Copy Example
class Address {
String city;
Address(String city) {
this.city = city;
}
}
class Person implements Cloneable {
String name;
Address address;
Person(String name, Address address) {
this.name = name;
this.address = address;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
public class ShallowCopyDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Address addr = new Address("Delhi");
Person p1 = new Person("Amit", addr);
Person p2 = (Person) p1.clone();
p2.name = "Ravi";
p2.address.city = "Mumbai"; // shared object
System.out.println(p1.name + " - " + p1.address.city); // Amit - Mumbai
System.out.println(p2.name + " - " + p2.address.city); // Ravi - Mumbai
}
}