Copy a primitive array in Java

In this post, we will see how to copy a primitive array into a new array in Java.


1. Naive

Naive solution would be to use a simple for loop to copy elements from the source array to destination array one at a time.

Download   Run Code


2. Arrays.copyOf()

static int[] copyOf(int[] original, int n)

Arrays class provides copyOf() method that copies first n elements of the specified source array into a new array and returns the new array. To copy the full array, we need to pass length of the original array.

Download   Run Code


3. Arrays.copyOfRange()

static int[] copyOfRange(int[] original, int from, int to)

Arrays also provides copyOfRange() method which is similar to copyOf() but instead of copying only first few elements, it copies the specified range of the specified array into a new array.

We can use it to copy the whole array by taking starting index as 0 and ending index equal to the length of the original array.

Download   Run Code


4. System.arraycopy()

static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n);

System.arraycopy() offers more flexibilty while copying an array. It copies a n elements from the specified source array src starting from srcPos position, to the destPos position of the destination array dest.

We can use it to copy the whole array as shown below:

Download   Run Code

Suggested Read: Copy an Object Array in Java

References: Arrays Javadoc SE 8

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of