Shallow copy or Deep copy?

From the link here

Shallow copies duplicate as little as possible. A shallow copy of a
collection is a copy of the collection structure, not the elements.
With a shallow copy, two collections now share the individual
elements.

Deep copies duplicate everything. A deep copy of a collection is two
collections with all of the elements in the original collection
duplicated.

Your example is creating a shallow copy.

A ob1 = new A();
ob1.a = 10;
A ob2 = new A();
ob2 = ob1;

ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 5.

Deep copy will be –

 A ob1 = new A();
 ob1.a = 10;
 A ob2 = new A();
 ob2.a = ob1.a;

 ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 10.

Leave a Comment