Interesting Java Facts 3: Cloning a multidimensional Array

Consider the following code

int arr[][]={{10,20,30},{23, 45, 67,}};
int clone[][]=arr.clone();
clone[0][0]=-1;

Q. What should be the value of arr[0][0] and clone [0][0]?

A. It is -1 for both. Why? Let understand 2 things- clone always make a shallow copy of object  & Array is an object in Java.

Shallow copy: When we clone an object in Java, it only creates duplicate copies of primitive types, and for objects, the reference is copied. For example if an Employee object containing an address object is cloned, for address only reference is copied, that is not bot employee and clone are referencing same address object and any change in address is reflected in both.

We can override the clone method for Employee to make sure whenever a clone is made a new object for Address is created as well and all the values are actually copied one by one to new object. This will make sure both the original object and clone are referencing to their own address and changes in one does not get reflected in other.

Array is an object: In java array is an object, so a multidimensional array is actually an object with multiple objects (arrays) in it.

Putting both the above concepts together, we can figure out that while cloning, only the references of array objects  in multidimensional array are copied to cloned object, that means any change in one will get reflected to another.