LeetCampus
Interview Question

What are shallow copy and deep copy in java?

July 24, 2025
0 views
Difficulty: Medium
Popularity: Common
Share on

Question Explanation

Shallow copy and deep copy are fundamental concepts in Java that pertain to how objects are copied. Understanding these concepts is crucial for developers, as it affects memory management and behavior of objects in applications. Interviewers often ask this question to assess a candidate's grasp of object-oriented programming principles and their ability to manage object references effectively. A shallow copy creates a new object, but instead of copying the objects that the original object references, it merely copies the references to those objects. This means that changes to mutable objects within the copied object will reflect in the original object. In contrast, a deep copy creates a completely independent copy of the original object and all objects it references, ensuring that changes to either object do not affect the other. This distinction is crucial in scenarios where objects contain other objects, such as in collections or complex data structures. Misunderstanding these concepts can lead to bugs, especially when dealing with mutable objects, as shared references can cause unintended side effects. A solid grasp of shallow and deep copies is not only important for coding interviews but also vital for writing robust and maintainable Java applications.

Sample Answers

Example 1: Shallow Copy in Action

In Java, a shallow copy can be created using the clone() method. When you call clone() on an object, it generates a new instance of that object, but the fields of the object that are references to other objects are copied as references, not as new instances. For instance, consider the following code:

class Person implements Cloneable {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Address {
    String city;

    Address(String city) {
        this.city = city;
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("New York");
        Person person1 = new Person("John", address);
        Person person2 = (Person) person1.clone();

        // Changing the address of person2
        person2.address.city = "Los Angeles";

        System.out.println(person1.address.city); // Outputs: Los Angeles
    }
}

In this example, modifying person2 affects person1 because both share the same Address reference.

Example 2: Deep Copy Implementation

To create a deep copy in Java, you need to manually copy all fields of the original object, including nested objects. This can be achieved through a combination of the clone() method and custom copy logic. Here’s an example:

class Person implements Cloneable {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    protected Object clone() throws CloneNotSupportedException {
        Person cloned = (Person) super.clone();
        cloned.address = (Address) address.clone(); // Deep copy of Address
        return cloned;
    }
}

class Address implements Cloneable {
    String city;

    Address(String city) {
        this.city = city;
    }

    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("New York");
        Person person1 = new Person("John", address);
        Person person2 = (Person) person1.clone();

        // Changing the address of person2
        person2.address.city = "Los Angeles";

        System.out.println(person1.address.city); // Outputs: New York
    }
}

In this code, when we clone person1, person2 gets a new Address object, ensuring changes to person2 do not affect person1.

Example 3: Practical Implications of Copy Types

Understanding the difference between shallow and deep copies is essential in real-world applications, especially when managing collections or complex data structures. For instance, in a scenario where you have a list of objects:

List<Person> people = new ArrayList<>();
people.add(new Person("Alice", new Address("Seattle")));
people.add(new Person("Bob", new Address("Chicago")));

If you perform a shallow copy of this list:

List<Person> shallowCopy = new ArrayList<>(people);

Any modification in the Address of shallowCopy will also reflect in the original people list. This can lead to unintended side effects, such as:

"Changing shared references can cause data integrity issues."

In contrast, if you implement a deep copy for each Person, you ensure that each copy maintains its own unique Address object. This is particularly important in applications that require data isolation, such as multithreaded environments or when implementing undo functionalities, where a state change should not affect previous states. Always analyze which type of copy is appropriate based on your application needs.

Keywords

Javashallow copydeep copyobject-oriented programmingmemory management

Ready to practice more questions?

Explore our collection of technical interview questions from top companies.

View All Questions