Objects in Java are passed by their reference.
Shallow copy: copies only the references of the members of the original object. The copy will still point to the same member instances. Therefore manipulating copy could change the state of original object.
Deep copy: duplicates everything by copying over the actual data to a newly allocated segment of memory. The copy will have complete new instance of all members. Therefore manipulating the copy will not affect the original object' state.
The following examples demonstrate the difference between shallow copy and deep copy using an array. Remember array variables are references in Java too.
The values array reference points to memory location of numbers. Therefore manipulating the items through either reference will result in unexpected changes:
Note that we did not change the array values inside the ShallowCopyExample class, the change was made through the input array. That can be very confusing.
To avoid this issue we will need to copy the array deeply instead:
Let's test to see whether or not we were correct:
Yes, the code works as expected. The arrays are deeply copies therefore their values will only change if they are manipulated through their only reference.