There are multiple solutions on how to copy an array in java depending on data type, methods preferred and also the elements we are interested to copy from an array. The trickiest part in copying an array if we are interested only on specific indexes. This can be solved by relying on static methods of java.util.Arrays class.

For each loop – Copy an array in java

This scenario is simply to copy all the elements of an array to another array by using the for loop. So basically what we needed to do is to iterate to all the values of an array and then put it on another array. Why we will go into trouble of iterating on each value while we can just use the equality for example target=source? This is simply because we want to put specific logic first before assigning the values to array. On this example source code in copying all elements of an array into another array, we will format first the elements before putting it into another array. One more reason is that if the elements of source object has been changed, the elements of target array will also change.

Sample Output:

Copy an array in java : Limited length

The following source code shows how to use the Arrays.copyOf(datatype[], length) method. This method is readily available on most of the data type, you can just modify the source input to your preferred data type. This method is essential if we are dealing with fixed array length. The method works in this way, when the array source is shorter than the length specified, array is padded with null characters. While if the source array is longer than the length defined then other elements are truncated.

Sample Output:

Copy an array in java : Specifying the index

This section of the tutorial will tackle on how to copy an array in java specifying the source index. Meaning to say we will copy only selected elements from the source array. With this source code we would be able to get only indexes that we want, like for instance we only want to get the middle elements of an array.  We will be using the Arrays.copyOfRange(original,from, to). This method accepts mos of the data types similar to the previous method that we have used. Depending on your business requirements, select the best data type the will suit your business requirements.

Sample Output: