Title: Deep Clone a 2D Array in Java
In this guide, you’ll learn how to create a true deep clone of a two-dimensional array in Java, one where changes to the copy never leak back into the original matrix. We’ll build a reusable deepClone method, trace it on a concrete input, and walk through the mistakes that trip up most developers the first time they try this.
Understanding the Problem
A Java int[][] is not really a grid, it is an array of references to separate int[] row arrays. Calling matrix.clone() only duplicates the outer array of references, so the new array and the original still point at the exact same row objects underneath.
That means mutating a single element through the ‘cloned’ matrix also changes the original, because both matrices share the same underlying row arrays. A deep clone has to allocate a brand new row array for every row, not just a new outer array, so the copy and the original become fully independent.
Approach / Algorithm Steps
- Check whether the
originalarray reference isnull, and returnnullimmediately if it is. - Create a new outer array
copywith the same number of rows asoriginal, usingnew int[original.length][]. - Loop through every row index
ifrom0tooriginal.length - 1. - For each row, check whether
original[i]isnullbefore touching it, since a jagged array may contain null rows. - If the row is not null, call
original[i].clone()to create a brand newint[]holding the same values. - Assign that freshly cloned (or null) row to
copy[i]. - After the loop finishes, return
copyas the fully independent deep-cloned 2D array.
Java Program
public class DeepClone2DArray {
public static int[][] deepClone(int[][] original) {
if (original == null) {
return null;
}
int[][] copy = new int[original.length][];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i] == null ? null : original[i].clone();
}
return copy;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] cloned = deepClone(matrix);
cloned[0][0] = 100;
System.out.println("Original: " + matrix[0][0]);
System.out.println("Cloned: " + cloned[0][0]);
}
}Explanation of the Program
deepClonefirst checks whetheroriginalisnulland returnsnullright away, so the rest of the method never has to guard against a null outer array.new int[original.length][]allocates only the outer array, leaving every row unset until the loop below fills them in.- The loop visits each row index
iand checksoriginal[i] == nullfirst, because a jagged array is allowed to mix real rows with null entries. - When a row is not null,
original[i].clone()produces a brand newint[]with the same length and values, completely detached from the source row. - Returning
copyhands back an array where every row is a fresh allocation, so no element ofcopyshares memory withoriginal.
Step-by-Step Trace
Trace deepClone on int[][] data = {{5, 9}, null, {2}}, which mixes a normal row, a null row, and a single-element row so every branch in the loop runs at least once.
| Iteration | original[i] | original[i] == null? | Action | copy[i] |
|---|---|---|---|---|
| 1 | {5, 9} | no | clone row | {5, 9} (new array) |
| 2 | null | yes | assign null | null |
| 3 | {2} | no | clone row | {2} (new array) |
At the end of each iteration, copy[i] is either null or a freshly allocated array holding the same values as original[i], never the same object reference.
Examples
Example 1: Cloning a Simple Matrix
Mutating a cloned matrix must never change the original. This example clones a 3×3 matrix and overwrites one element in the copy to confirm the two arrays no longer share memory.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] cloned = DeepClone2DArray.deepClone(matrix);
cloned[0][0] = 100;
System.out.println(matrix[0][0]); // 1
System.out.println(cloned[0][0]); // 100Example 2: Cloning a Jagged Array
Rows do not need to be the same length. Because deepClone relies on each row’s own length through clone(), it works on jagged arrays without any extra bookkeeping.
int[][] jagged = {
{1},
{2, 3, 4},
{5, 6}
};
int[][] clonedJagged = DeepClone2DArray.deepClone(jagged);
clonedJagged[1][0] = 99;
System.out.println(jagged[1][0]); // 2
System.out.println(clonedJagged[1][0]); // 99
System.out.println(clonedJagged[2].length); // 2Example 3: Why matrix.clone() Alone Is Not Enough
This example shows the pitfall directly. Cloning only the outer array still leaves the rows shared, so a mutation through the ‘shallow clone’ corrupts the original too.
int[][] original = {{1, 2}, {3, 4}};
int[][] shallow = original.clone();
shallow[0][0] = 999;
System.out.println(original[0][0]); // 999, the original changed too!Common Mistakes to Avoid
Most bugs in 2D array cloning come from stopping one level too shallow. Watch for these specific traps.
- Calling only matrix.clone() – produces a new outer array, but every row still points at the original’s row objects, so mutating a cloned row also mutates the source. Clone each row individually instead of relying on one outer
clone(). - Skipping the null-row check – calling
original[i].clone()directly on a jagged array that contains a null row throws aNullPointerException. Guard each row withoriginal[i] == null ? null : original[i].clone(). - Assuming a fixed column count – allocating
new int[rows][cols]up front and copying element by element breaks on jagged arrays whose rows differ in length. Let each row’s own length drive the copy, which is exactly whatclone()does. - Using Arrays.copyOf on the outer array only – like
clone(),Arrays.copyOf(original, original.length)only duplicates references to the inner rows, so it is still a shallow copy that shares mutable state. - Reaching for serialization-based deep copy – wrapping the matrix in
ObjectOutputStreamto force a deep copy works, but for a 2D primitive array it adds serialization overhead for a result that per-rowclone()already gives you for free.
Edge Cases to Test
A thorough test pass for deepClone should cover these input shapes.
- Null outer array reference
- Empty outer array (zero rows)
- Row with zero-length array
- Null row inside a jagged array
- Single row with a single element
- All rows identical in values
- Jagged array with widely varying row lengths
- Very large matrix, to confirm performance stays linear
Additional Considerations
The algorithm runs in O(n * m) time and uses O(n * m) extra space, where n is the number of rows and m is the average row length, because every element must be visited exactly once to be copied into the new array.
For 2D arrays of primitives, int[].clone() per row is the fastest deep-copy mechanism available. An equivalent one-liner is Arrays.stream(original).map(int[]::clone).toArray(int[][]::new), but it allocates an extra stream pipeline for no real benefit over the explicit loop shown above.
This same per-row clone() trick only works because int is a primitive. If the matrix held objects, such as String[][] or a custom class, cloning the row array would still only copy references to those objects, so mutable elements would need their own copy logic.
Interview Follow-up Questions
Once you can explain the shallow-clone pitfall, interviewers usually push the problem in one of these directions.
- What if the 2D array stores objects instead of primitives, like String[][] or custom objects? – cloning the outer array and each row only copies references to those objects; if the objects are mutable, deep-copy each element individually, for example through a copy constructor.
- What if the array is three-dimensional or has arbitrary depth? – recurse one dimension at a time, cloning the innermost primitive rows first and rebuilding each outer level from the already-cloned sub-arrays.
- What if the matrix is too large to duplicate fully in memory? – consider a copy-on-write strategy that shares rows until one is actually mutated, then clones only that row, trading extra bookkeeping for lower peak memory use.
- What if the clone must happen without using Arrays or Object.clone()? – manually allocate
new int[rows][]and copy each row with a bare nested for loop over indices, which works identically when library helpers are off limits.
Conclusion
Deep cloning a 2D array in Java comes down to one rule: clone every row, not just the outer array. Once deepClone handles the null checks for both the array and its rows, it works correctly on rectangular matrices and jagged arrays alike.
Try adapting this deepClone method to double[][] or char[][] to confirm the same pattern holds for any primitive 2D array. You can learn more about array-based problems in our Arrays category.



