2D Array Shallow Copy with Clone
What does the above program print and why?
public class ArrayCopy {
public static void changeArray(int[][] arr) {
int[][] copy = arr.clone(); // Shallow copy
copy[0][0] = 100;
}
public static void main(String[] args) {
int[][] data = { {1, 2}, {3, 4} };
changeArray(data);
System.out.println(data[0][0]);
}
}
A
0, because the array elements are reinitialized to 0.
B
1, because arr.clone() creates a deep copy, leaving the original array unchanged.
C
A compilation error occurs due to improper cloning of a 2D array.
D
100, because arr.clone() creates a shallow copy that still shares inner arrays with the original.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE