Last Updated:

How do I copy an array to Java?

Methods of copying an array in Java

Object.clone() - You can use this method to fully copy an array. This method will not work for you if you want to partially copy the array.

System.arraycopy() is the best way to make a partial copy of an array. The method defines the following parameters: an array, the elements of which will be copied; Which index to copy items from. The resulting array the first element of the resulting array and the total number of elements to copy.

For example, System.arraycopy (source, 3, destination, 2, 5) - 5 elements will be copied from the source array to the resulting array, starting from the 3rd index of the source in index 2 of the resulting array.

Arrays.copyOf() - If you want to copy the first few elements of an array or make a full copy of the array, you can use this method. True, it is not as versatile as System.arraycopy(), but it is just as easy to use.

Arrays.copyOfRange() is another useful method for partially copying an array.

That's all the useful methods for full and partial copying of the array. Note that all built-in methods for copying are only available for one-dimensional arrays. Now let's see these methods in action:

JavaArrayCopyExample.java

The result of the program: