Java : Shallow Cloning Vs Deep Cloning

Pre-requisite : 

Below are  the list of differences between shallow cloning and deep cloning in java.

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Cloning

  • Cloned Object and original object are not 100% disjoint.
  • Any changes made to cloned object will be reflected in original object or vice versa.
  • Default version of clone method creates the shallow copy of an object.
  • Shallow copy is preferred if an object has only primitive fields.
  • Shallow copy is fast and also less expensive.

Example: Shallow Cloning Example

Deep Cloning

  • Cloned Object and original object are 100% disjoint.
  • Any changes made to cloned object will not be reflected in original object or vice versa.
  • To create the deep copy of an object, you have to override clone method.
  • Deep copy is preferred if an object has references to other objects as fields.
  • Deep copy is slow and very expensive.

Example: Deep Cloning Example