Shallow vs Deep copy in Java

When creating copies of arrays or objects one can make a deep copy or a shallow copy.

Shallow Copy

import java.util.Arrays;

public class ShallowAndDeep2 {

	public static void main(String[] args) {
		
		int[] arr1 = { 1, 2, 3, 4, 5, 6 };		
		
		// Printing array elements
		System.out.println("arr1 : " + Arrays.toString(arr1));
		int[] arr2 = arr1; // Shallow Copy, both arrays points to same memory locations
		
		// one value of array2 changed, but while both array points to same location, values of arr1 are also same
		arr2[2] = 10; 

		System.out.println("arr2 : " + Arrays.toString(arr2));
		System.out.println("arr1 again : " + Arrays.toString(arr1));
	}
}

Output

arr1 : [1, 2, 3, 4, 5, 6]
arr2 : [1, 2, 10, 4, 5, 6]
arr1 again : [1, 2, 10, 4, 5, 6]

In above example we have changed the value of arr1[2] to 10. Since it’s a shallow copy so corresponding arr1 values are also changed.

Deep Copy

import java.util.Arrays;

public class ShallowAndDeep2 {

	public static void main(String[] args) {

		int[] arr1 = { 1, 2, 3, 4, 5, 6 };

		// Printing array elements
		System.out.println("arr1 : " + Arrays.toString(arr1));
		int[] arr2 = new int[arr1.length];

		// Deep copy, copying elements one by one 
		for (int a = 0; a < arr1.length; a++)
			arr2[a] = arr1[a];

		// one value of array2 changed, and only value for arr1 will be changed
		// values of arr1 and arr2 are not same
		arr2[2] = 10;

		System.out.println("arr2 : " + Arrays.toString(arr2));
		System.out.println("arr1 again : " + Arrays.toString(arr1));
	}
}

Output

arr1 : [1, 2, 3, 4, 5, 6]
arr2 : [1, 2, 10, 4, 5, 6]
arr1 again : [1, 2, 3, 4, 5, 6]

Leave a Reply

Your email address will not be published. Required fields are marked *