Advertisement
Home Data Structure Arrays Clone an Array in Java

Clone an Array in Java

1
Advertisement

Title: Clone an Array in Java

Cloning an array in Java means creating a brand new array object that holds the same values as the original, so that changing one does not affect the other. In this guide, you will learn the built-in ways Java gives you to copy an array, where each one falls short, and how to safely clone multidimensional or object arrays.

Arrays in Java are objects, so a simple assignment like int[] copy = original; just creates a second reference to the same underlying array. Any change through copy shows up through original too, which is rarely what you want. You’ll build a small program that demonstrates the correct approach, then walk through the trickier case of nested arrays.

Approach to Cloning an Array

  1. Decide whether the array holds primitives (int, double, and so on) or references to objects, because that decision determines whether a shallow copy is enough.
  2. For a one-dimensional primitive array, call array.clone() to get a new array backed by its own memory.
  3. Use Arrays.copyOf(array, newLength) when you want a copy that can also grow or shrink during the copy.
  4. Use System.arraycopy(src, 0, dest, 0, length) when you already have a destination array and want to copy into it directly.
  5. For a two-dimensional or jagged array, clone the outer array first, then clone each inner row individually, since clone() only copies one level deep.
  6. For an array of mutable objects, clone each element as well if the objects themselves must be independent, not just the array container.
  7. Confirm independence by mutating the copy and checking that the original array (and its objects) are unaffected.

Java Program

The program below defines two helper methods: cloneArray for a flat int[], and deepClone2D for a two-dimensional array that also protects against null rows inside a jagged array.

Java
import java.util.Arrays;

public class CloneArrayExample {

    public static int[] cloneArray(int[] source) {
        return source.clone();
    }

    public static int[][] deepClone2D(int[][] source) {
        if (source == null) {
            return null;
        }
        int[][] result = new int[source.length][];
        for (int i = 0; i < source.length; i++) {
            result[i] = (source[i] == null) ? null : source[i].clone();
        }
        return result;
    }

    public static void main(String[] args) {
        int[] original = {10, 20, 30, 40, 50};
        int[] copy = cloneArray(original);
        copy[0] = 999;

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Clone: " + Arrays.toString(copy));

        int[][] grid = {{1, 2}, {3, 4}};
        int[][] gridCopy = deepClone2D(grid);
        gridCopy[0][0] = 777;

        System.out.println("Original grid row 0: " + Arrays.toString(grid[0]));
        System.out.println("Cloned grid row 0: " + Arrays.toString(gridCopy[0]));
    }
}

Explanation of the Program

cloneArray simply calls source.clone(), which Java implements for array types to allocate a new array of the same length and copy every element across. For primitives, that single call is already a complete, independent copy.

deepClone2D cannot stop at one clone() call. The outer new int[source.length][] creates a fresh array of row references, but each row still needs its own clone() so the rows do not stay shared with the original.

The ternary inside the loop, (source[i] == null) ? null : source[i].clone(), protects against jagged arrays where a row was never initialized. Skipping this check would throw a NullPointerException the moment a null row is cloned.

In main, mutating copy[0] and gridCopy[0][0] after cloning proves that neither the flat array nor the nested row array is shared with the original.

Step-by-Step Trace

Consider calling deepClone2D on the jagged array {{7, 8}, null, {9}}, which has three rows: a normal row, a null row, and a single-element row.

Iterationsource[i]source[i] == null?result[i] (after)
1{7, 8}noclone of {7, 8}
2nullyesnull
3{9}noclone of {9}

At the end of iteration i, result[i] holds either an independent clone of source[i] or null if the row was never initialized, never a shared reference to the original row.

Examples

Example 1: Cloning with Arrays.copyOf

Arrays.copyOf(array, length) behaves like clone() but also lets you resize the result, which is handy when you want to copy and pad or truncate in one step.

Java
public class CopyOfExample {
    public static void main(String[] args) {
        int[] source = {3, 6, 9};
        int[] copy = java.util.Arrays.copyOf(source, source.length);
        copy[1] = 60;

        System.out.println(java.util.Arrays.toString(source)); // [3, 6, 9]
        System.out.println(java.util.Arrays.toString(copy));   // [3, 60, 9]
    }
}

Example 2: Cloning with System.arraycopy

System.arraycopy copies into a destination array you already created, which is useful when merging ranges or working with a reusable buffer.

Java
public class ArrayCopyExample {
    public static void main(String[] args) {
        int[] source = {1, 2, 3, 4};
        int[] destination = new int[source.length];
        System.arraycopy(source, 0, destination, 0, source.length);
        destination[0] = 100;

        System.out.println(java.util.Arrays.toString(source));      // [1, 2, 3, 4]
        System.out.println(java.util.Arrays.toString(destination)); // [100, 2, 3, 4]
    }
}

Example 3: Why Object Arrays Still Share State

Cloning an array of objects only copies the references, not the objects they point to. Mutating a field through the clone still changes the same object the original array points to.

Java
public class SharedReferenceExample {
    static class Point {
        int x;
        Point(int x) { this.x = x; }
    }

    public static void main(String[] args) {
        Point[] original = {new Point(1), new Point(2)};
        Point[] shallowCopy = original.clone();
        shallowCopy[0].x = 99;

        System.out.println(original[0].x);    // 99, same object was mutated
        System.out.println(shallowCopy[0].x);  // 99
    }
}

Common Mistakes to Avoid

These are the mistakes that trip up most learners the first time they try to clone an array in Java.

  • Assuming clone() is always a deep copy – mutating a nested row or a referenced object through the clone also changes the original. Clone each nested array or object individually when true independence is required.
  • Using plain assignment instead of clone() – int[] copy = original; just creates a second name for the same array, so a later copy[i] = x change is visible through original too. Always call .clone(), Arrays.copyOf(), or System.arraycopy() to get a distinct backing array.
  • Forgetting null rows in a jagged array – calling row.clone() on a row that was never initialized throws a NullPointerException. Check each row for null before cloning it.
  • Passing the wrong length to System.arraycopy – supplying a length larger than either array’s size throws ArrayIndexOutOfBoundsException. Pass Math.min(source.length, destination.length) or the exact length you intend to copy.
  • Treating an object array clone as a deep copy of its elements – the array itself is new, but every element still points to the same object as the original array. Clone or rebuild each element if the objects must be independent too.

Edge Cases to Test

Before calling the cloning logic done, walk through these input shapes.

  • Empty array (length 0)
  • Null array reference
  • Single-element array
  • Jagged 2D array with one or more null rows
  • Array of primitives versus array of mutable objects
  • Very large array where copy cost matters
  • Array containing duplicate or repeated values

Additional Considerations

Every cloning approach covered here (clone(), Arrays.copyOf, and System.arraycopy) runs in O(n) time and needs O(n) extra space, since a genuinely independent copy must allocate a new backing array the same size as the original.

Deep cloning a two-dimensional array costs O(rows x columns) space, because every row needs its own fresh array in addition to the outer array of row references.

Arrays.copyOf is the most flexible choice when the result length can differ from the source, while System.arraycopy is fastest when copying into an already-allocated buffer, since it skips creating a new array.

For arrays of custom objects, consider giving the class a copy constructor instead of relying on the default shallow clone(), so callers get real independence without reimplementing the deep-copy logic every time.

Interview Follow-up Questions

An interviewer rarely stops at the basic clone. Expect at least one of these variations.

  • What if the array holds mutable custom objects and you need a true deep copy? – give each object a copy constructor, or implement Cloneable on the object itself and call it for every element.
  • What if the array is three-dimensional or deeper? – recurse one level further: clone the outer array, then apply the same two-dimensional cloning logic again to each inner array.
  • What if you are returning an internal array from a getter and must not let callers mutate your state? – return a clone from the getter, so the caller only ever sees a defensive copy, never your live internal array.
  • What if you cannot allocate extra memory for a full copy? – a true clone fundamentally needs O(n) extra space, so consider copy-on-write instead, sharing the original array until the first write forces an actual copy.
  • What if the data arrives as a stream of chunks instead of one complete array? – accumulate chunks into a growable buffer and only materialize (and clone, if needed) the final array once the stream ends.

Conclusion

Cloning an array in Java is straightforward for primitives: clone(), Arrays.copyOf(), and System.arraycopy() all give you an independent one-dimensional copy. The part learners miss is that none of these go deeper than one level, so nested arrays and referenced objects still need to be cloned explicitly.

Try adapting deepClone2D to a three-dimensional array, or to an array of your own class, to make sure the independence really holds all the way down. You can learn more about working with arrays in Java in our Arrays category.