![]() |
VOOZH | about |
In object-oriented programming, object copying refers to creating a new object using an existing object’s data. In Java, this is commonly done using constructors, the clone() method, or custom logic, and is closely related to cloning and reference handling.
Based on how data is copied, object copying is classified into:
A shallow copy creates a new object but does not duplicate referenced objects; instead, it copies their references. As a result, both the original and copied objects point to the same memory location for reference fields.
Explanation:
This can lead to unpleasant side effects if the elements of values are changed via some other reference.
Output:
[3, 7, 9]
[13, 7, 9]
Explanation: Both vals and data refer to the same array. Any modification through one reference affects the other.
A deep copy creates a new object along with separate copies of all referenced objects, ensuring complete independence between the original and copied objects. Any change made to one object does not affect the other.
Explanation:
Output:
[3, 7, 9]
[3, 7, 9]
Explanation: A new array is created and values are copied individually. Changes to vals do not affect data.
Lazy copy is a hybrid approach of shallow copy and deep copy. Initially, multiple objects share the same data using a shallow copy. A deep copy is created only when a write operation is performed on any one of the objects. This technique is also known as copy-on-write.
Explanation:
Output:
3 7 9
3 7 10
Explanation:
Scenario | Recommended Copy |
|---|---|
Only primitive fields | Shallow Copy |
Mutable reference fields | Deep Copy |
Performance-critical systems | Lazy Copy |
Immutable objects | Shallow Copy |
Note:
- Shallow copy is faster but unsafe for mutable objects
- Deep copy ensures isolation but costs memory
- Lazy copy balances performance and safety