Difference between Shallow Copy and Deep Copy in Java with Example

Most of the java developers are aware of clone() method of Object class in java. But very few are  aware of types of cloning methods in java. There are two types of cloning in java, one is shallow copy and other is deep copy. In this article I will share the difference between Shallow copy and Deep copy with examples.So let's check it out first, what is cloning.

Read Also : Java Programming Interview Questions and Answers

What is Cloning?

Cloning is a process of creating an exact copy of the existing object in java heap memory. It creates a new object of the same class as the existing object and initializes all its data members using field to field mapping. The resultant object is thus called clone or copy of the original object.

In Java, only the objects of a class that implements Cloneable interface can be cloned or copied. clone() method of java.lang.Object can be used to achieve the desired type of copy of the object (shallow copy or deep copy).

Shallow Copy

1. If we simply use clone method defined in java.lang.Object class for object copying, the resultant object copy is known as Shallow copy of the original object.

2. If the class contains a mix of primitive and non-primitive data types such an object type field, the primitive variable values are copied directly from the original object to the copy object but, in case of the reference object fields, only the reference of object field is copied into the clone’s referenced field and not the exact referenced object. In such cases, the references of the object field of both the original as well as the clone object point to the same object in the memory location. The changes made to the referenced fields in original object reflect in the referenced fields of the clone and vice-versa.

3. Shallow copy is same as deep copy if the object class consists entirely of primitive data type fields.

4. Shallow copy of the object may not be completely independent of the original object (cases when referenced type is also present in the object class).


public class ShallowCopyExample {

 public static void main(String[] args) {
  // Creating original Employee object
  Company cmp = new Company("Google", "Bengaluru");
  Employee originalEmployee = new Employee("John", 25, cmp);
  System.out.println(originalEmployee.name+" " 
                                  +originalEmployee.age+" " 
                                  +originalEmployee.company.companyName+" " 
                                  +originalEmployee.company.location);
  
  // Creating shallow copy of original Employee object
  try {
   Employee employeeCopy = (Employee) originalEmployee.clone(); 
 
   /*changing the companyName field in 
     referenced field of clone object */
   employeeCopy.company.companyName="Facebook"; 
 
   System.out.println("After changing company name of copy object:");
   System.out.println("Original object:");
   System.out.println(originalEmployee.name+" " 
                                          +originalEmployee.age+" " 
                                          +originalEmployee.company.companyName+" " 
                                          +originalEmployee.company.location);
   System.out.println("Clone object (Shallow copy):");
   System.out.println(employeeCopy.name+" " 
                                           +employeeCopy.age+" " 
                                           +employeeCopy.company.companyName+" " 
                                           +employeeCopy.company.location);
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }    
 }
}

class Employee implements Cloneable{
 String name;
 int age;
 Company company;
 public Employee(String name, int age, Company company) {
  super();
  this.name = name;
  this.age = age;
  this.company = company;
 }
 
 //Default clone() method
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 } 
 
}

class Company{
 String companyName;
 String location;
 public Company(String companyName, String location) {
  super();
  this.companyName = companyName;
  this.location = location;
 }
}


Output: 
John 25 Google Bengaluru
After changing company name of copy object:
Original object:
John 25 Facebook Bengaluru
Clone object (Shallow copy):
John 25 Facebook Bengaluru

As you can see in the above example, we created an Employee object referenced by originalEmployee variable and its copy object referenced by employeeCopy variable. When we changed the “companyName” field of the referenced field “company” in clone object, the change reflected in both the objects. So, in this case the clone object is not independent of the original object.

Shallow copy in java

Deep Copy

1. A Deep Copy of the original object is said to have been created when all the primitive/referenced fields are copied to the clone object. If there are any object fields that are referenced in the original object, then a copy of such reference field is created by calling clone() method on such fields and this copy is passed onto the clone object such that the referenced object fields in both original as well as the clone object point to different objects.

2. Whenever deep copy of an object is created, it is completely independent of the original object.  


public class DeepCopyExample {

 public static void main(String[] args) {
  // Creating original Employee object
  Company cmp = new Company("Google", "Bengaluru");
  Employee originalEmployee = new Employee("John", 25, cmp);
  System.out.println(originalEmployee.name + " "  + 
                                   originalEmployee.age + " "+
                                   originalEmployee.company.companyName + " " +
                                   originalEmployee.company.location);

  // Creating deep copy of original Employee object
  try {
   Employee employeeCopy = (Employee) originalEmployee.clone(); 
 
   /*changing the companyName field in 
     referenced field of clone object */
   employeeCopy.company.companyName = "Facebook"; 
 
   System.out.println("After changing company name of copy object:");
   System.out.println("Original object:");
   System.out.println(originalEmployee.name + " " + 
                                           originalEmployee.age + " " + 
                                           originalEmployee.company.companyName + " " +
                                           originalEmployee.company.location);
   System.out.println("Clone object (Deep copy):");
   System.out.println(employeeCopy.name + " " + 
                                           employeeCopy.age + " " + 
                                           employeeCopy.company.companyName + " " +
        employeeCopy.company.location);
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
 }
}

class Employee implements Cloneable {
 String name;
 int age;
 Company company;

 public Employee(String name, int age, Company company) {
  super();
  this.name = name;
  this.age = age;
  this.company = company;
 }

 // Default clone() method
 @Override
 protected Object clone() throws CloneNotSupportedException {
  Employee employee = (Employee) super.clone();
  employee.company = (Company) company.clone();
  return employee;
 }

}

class Company implements Cloneable {
 String companyName;
 String location;

 public Company(String companyName, String location) {
  super();
  this.companyName = companyName;
  this.location = location;
 }

 // Default clone() method
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 }

}


Output:
John 25 Google Bengaluru
After changing company name of copy object:
Original object:
John 25 Google Bengaluru
Clone object (Deep copy):
John 25 Facebook Bengaluru

As you can see in the above example, when the “companyName” field of the referenced object field “company” in copy object is changed, it changes just the relevant field in clone object and the changes are not reflect in the original object’s reference object field. The clone object and the original object are completely different.



Recap : Difference between Shallow Copy and Deep Copy in Java


Shallow CopyDeep Copy
ChangesChanges made to the cloned object will be shown in the original object or vice-versaChanges made to the cloned object will not be shown in the original object and vice-versa.
CreationBy default shallow copy of the object is created when you use clone() method.To create a deep copy of the object you need to override the clone() method.
DisjointOriginal object and cloned object are not 100% disjointBoth original object and cloned object are 100% disjoint
PerformanceShallow copy is fast and uses less memoryDeep copy is slow and uses more memory

That's all for the topic difference between Shallow copy and Deep copy in java with examples. If you like the article then please share it with your friends.

References :
Java docs

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry