Best Way to Copy an Array in Java

What is the best way to copy an array in Java?

I have an array a that keeps getting updated. For example, a = [1,2,3,4,5]. I need to create an exact copy of a and store it in b, so that even if a changes to [6,7,8,9,10], b should still hold [1,2,3,4,5]. I tried using a loop like:

for(int i=0; i<5; i++) {  
    b[i] = a[i];  
}

But it doesn’t seem to work as expected. What is the correct way to copy an array in Java without using complex terms?

If you’re looking for a simple, built-in way to copy an array in Java, Arrays.copyOf() is your best friend.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = Arrays.copyOf(a, a.length);

        // Modify 'a' to check if 'b' remains unchanged
        a[0] = 99;

        System.out.println(Arrays.toString(a)); // [99, 2, 3, 4, 5]
        System.out.println(Arrays.toString(b)); // [1, 2, 3, 4, 5] (unchanged)
    }
}

:white_check_mark: Why use this?

  • Short and efficient—no need to write a loop manually.
  • Creates a completely new array, so changes in a don’t affect b.

:rotating_light: When to avoid?

  • If you need a deep copy (for arrays of objects), this won’t be enough.

Arrays.copyOf() is great, but if you’re dealing with large arrays and need better performance, System.arraycopy() is the way to go.

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = new int[a.length];

        System.arraycopy(a, 0, b, 0, a.length);

        a[0] = 99; // Modify original array

        System.out.println(java.util.Arrays.toString(a)); // [99, 2, 3, 4, 5]
        System.out.println(java.util.Arrays.toString(b)); // [1, 2, 3, 4, 5] (unchanged)
    }
}

:white_check_mark: Why use this?

  • Faster than loops, especially for large arrays.
  • More flexible—you can copy only a specific range if needed.

:rotating_light: When to avoid?

  • For small arrays, Arrays.copyOf() is simpler.

There’s also the clone() method, which is a quick way to copy an array in Java.

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = a.clone();

        a[0] = 99; // Modify original array

        System.out.println(java.util.Arrays.toString(a)); // [99, 2, 3, 4, 5]
        System.out.println(java.util.Arrays.toString(b)); // [1, 2, 3, 4, 5] (unchanged)
    }
}

:white_check_mark: Why use this?

  • Simple and fast—like Arrays.copyOf().
  • Works great for primitive arrays (e.g., int[], double[]).

:rotating_light: When to avoid?

  • If the array contains objects, clone() only copies references (shallow copy).