Shallow Copy vs Deep Copy in Java
Have you ever wondered why some changes to Java objects seem to "bleed" through to other objects while others don't? Understanding the difference between shallow copy and deep copy is crucial for any Java developer. In this guide, we’ll explore t...

class ShallowCopyExample implements Cloneable {
int value;
int[] array;
public ShallowCopyExample(int value, int[] array) {
this.value = value;
this.array = array;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
int[] array = {1, 2, 3};
ShallowCopyExample original = new ShallowCopyExample(10, array);
ShallowCopyExample copy = (ShallowCopyExample) original.clone();
System.out.println("Original array before change: " + original.array[0]); // 1
copy.array[0] = 99;
System.out.println("Original array after change: " + original.array[0]); // 99
}
}
- Pros: Fast and memory-efficient, useful for simple objects.
- Cons: Not ideal for objects with nested or mutable references.
class DeepCopyExample {
int value;
int[] array;
public DeepCopyExample(int value, int[] array) {
this.value = value;
this.array = array.clone();
}
}
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
DeepCopyExample original = new DeepCopyExample(10, array);
DeepCopyExample copy = new DeepCopyExample(original.value, original.array);
System.out.println("Original array before change: " + original.array[0]); // 1
copy.array[0] = 99;
System.out.println("Original array after change: " + original.array[0]); // 1
}
}
- Pros: Prevents unintended modifications to the original data.
- Cons: Can be slower and more memory-intensive than shallow copies, especially for large, deeply nested objects.
Read more at : Shallow Copy vs Deep Copy in Java
About the author
I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
Comments
Join the discussionNo comments yet. Be the first to comment.





