Shallow Copy and Deep Copy
About Shallow Copy
About Deep Copy
Sample Example
Example 1
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person original = new Person("Alice", 30);
// Shallow copy
Person shallowCopy = original;
shallowCopy.age = 25; // Changes reflected in both objects
System.out.println(original.age); // Output: 25
// Deep copy
Person deepCopy = new Person(original.name, original.age);
deepCopy.age = 35; // Changes not reflected in original
System.out.println(original.age); // Output: 25
System.out.println(deepCopy.age); // Output: 35
}
}Example 2
Example 3
Last updated