Shallow Copy vs Deep Copy in Java: An Important Interview Question and Must-Know Concept

In Java, the terms shallow copy and deep copy refer to how objects are duplicated and how references are handled when copying objects.

1. Shallow Copy

A shallow copy creates a new object, but instead of copying the actual contents (such as nested objects), it simply copies references to the original object's fields. In other words, the references in the copied object point to the same objects as the references in the original object. Therefore, if the original object has nested objects (like arrays or other objects), those nested objects are not copied, and both the original and the copied object will point to the same nested objects.

  • When to use: Use a shallow copy when you want to duplicate the outer structure of the object, but you don't need to duplicate the internal objects. Changes made to the nested objects in the shallow copy will also reflect in the original object and vice versa.

Example of Shallow Copy:

class Person {

String name;

int[] scores;


public Person(String name, int[] scores) {

this.name = name;

this.scores = scores;

}

}


public class Main {

public static void main(String[] args) {

int[] scores = {90, 80, 70};

Person p1 = new Person("Alice", scores);


// Create a shallow copy

Person p2 = p1; // This is shallow copying, just copying the reference


p2.name = "Bob";

p2.scores[0] = 100;


// Both p1 and p2 refer to the same object for the 'scores' array

System.out.println(p1.name); // Bob

System.out.println(p1.scores[0]); // 100 (changes in p2 reflect in p1)

}

}

In this case:

  • Changing p2.name to "Bob" also changes p1.name.
  • Modifying p2.scores[0] affects the array in p1 because they both reference the same array.

2. Deep Copy

A deep copy creates a new object and recursively copies all objects referenced by the original object, including nested objects. In a deep copy, each object in the original hierarchy is duplicated, so the new object does not share any references with the original object. Changes to nested objects in the deep copy do not affect the original object, and vice versa.

  • When to use: Use a deep copy when you want to fully duplicate the original object, including any objects that are referenced by it (deeply nested objects), and ensure that modifications to the copied object do not affect the original object.

Example of Deep Copy:

class Person {

String name;

int[] scores;


public Person(String name, int[] scores) {

this.name = name;

// Perform a deep copy of the scores array

this.scores = scores.clone(); // This creates a new array, copying the                                                     content

}

}


public class Main {

public static void main(String[] args) {

int[] scores = {90, 80, 70};

Person p1 = new Person("Alice", scores);


// Create a deep copy

Person p2 = new Person(p1.name, p1.scores.clone());


p2.name = "Bob";

p2.scores[0] = 100;


// The deep copy means changes to p2 do not affect p1

System.out.println(p1.name); // Alice

System.out.println(p1.scores[0]); // 90

}

}

In this case:

  • The scores array is cloned when creating the deep copy, so p1.scores and p2.scores are different arrays.
  • Changing p2.scores[0] does not affect p1.scores.

Summary of Differences:

  • Shallow Copy:
    • Copies only the outer object, but not nested objects.
    • Changes in the copied object can affect the original object if the objects inside it are mutable.
    • Usually achieved by assigning the reference or using clone() for simple objects.
  • Deep Copy:
    • Creates copies of all objects, including any nested objects.
    • Changes in the copied object do not affect the original object, as they are completely independent.
    • Achieved using object cloning and manual recursion for deeply nested objects.

In practice, you can use clone() for both shallow and deep copies, but for a deep copy, you’ll need to override the clone() method to handle nested object cloning as well.

#JavaInterviewQuestions #JavaConcepts #ShallowCopy #DeepCopy #JavaProgramming #CodingInterview #JavaTips #ObjectCloning #InterviewPrep #JavaDevelopers

Post a Comment

Previous Post Next Post