In Java, copying an object can be done in two ways: Shallow Copy and Deep Copy. These concepts are very important when working with object cloning and memory management.
🔹 Shallow Copy
A Shallow Copy creates a new object but copies references of nested objects instead of creating new ones.
👉 Both original and copied objects refer to the same memory location for referenced objects.
Characteristics
- Copies primitive values directly
- Copies object references
- Faster performance
- Changes in referenced objects affect both copies
Example
java id="3fp8b0"
class Address {
String city;
}
class Student implements Cloneable {
int id;
Address address;
public Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
🔹 Deep Copy
A Deep Copy creates a completely independent duplicate of the object including all referenced objects.
👉 Separate memory is allocated for all objects.
Characteristics
- Copies primitive values
- Creates new objects for references
- Safer but slightly slower
- Changes in one object do not affect the other
Example
java id="s8ld3v"
class Address {
String city;
}
class Student implements Cloneable {
int id;
Address address;
public Object clone() throws CloneNotSupportedException {
Student s = (Student) super.clone();
s.address = new Address();
s.address.city = this.address.city;
return s; // Deep copy
}
}
🔹 Key Differences
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Object Creation | Partial copy | Complete copy |
| Reference Objects | Shared | Independent |
| Memory Usage | Less | More |
| Performance | Faster | Slightly slower |
| Data Safety | Low | High |
| Object Dependency | Linked | Fully separate |
✅ Promotional Content
To master advanced Java concepts like object cloning, memory handling, collections, and real-time application development, join the Top Java Real Time Projects Online Training in Ameerpet.
Top comments (0)