Array Copy in Java | Example Program

To copy elements of one array into another array in java, we have to copy the array’s individual elements into another array.

In Java, we can use an assignment operator (=) to copy primitive data type variables, but not arrays are copied using assignment operator.

Assigning one array variable to another array variable actually copies one object reference to another and makes both reference variables point to the same memory location. For example:

array2 = array1;

Here, this statement does not copy elements of the array referenced (i.e. pointed) by array1 to array2. It merely copies the reference value from array1 to array2 because array variables do not themselves hold array elements. They hold a reference to the actual array.

Since array1 and array2 reference the same array, the previous array pointed by array2 is no longer referenced. Now it becomes garbage which will be automatically collected by garbage collection. Look at the below figure.

Array copy in Java

Ways to copy array elements from one Array into another Array in Java


There are mainly three ways by which we can copy array elements from one array into another array. They are as follows:

1. Using for loop to copy individual elements one by one.
2. Using the static arraycopy() method provided by the System class.
3. Using the clone method to copy arrays.

Let’s understand each method one by one.

1. Using for loop to copy individual elements one by one:

This is the simplest and correct method to copy array elements individually one by one from one array into another array. Let’s take an example program based on it.

Program source code 1:

package arraysProgram;
public class CopyArrayUsingLoop {
public static void main(String[] args) 
{
   int[ ] originalArray = {2, 3, 4, 5, 6, 7};
// Create an array newArray[] of same size as originalArray[].
    int[ ] newArray = new int[originalArray.length];
// Copy array elements from originalArray[] into newArray[].  
     for (int i = 0; i < originalArray.length; i++) 
        newArray[i] = originalArray[i];
 
   System.out.println("Elements of originalArray[]: ");
   for (int i = 0; i < originalArray.length; i++)
       System.out.print(originalArray[i] + " ");

   System.out.println("\n\nElements of newArray[]: ");
   for (int i = 0; i < newArray.length; i++)
       System.out.print(newArray[i] + " ");
 }
}
Output:
          Elements of originalArray[]: 
          2 3 4 5 6 7 

          Elements of newArray[]: 
          2 3 4 5 6 7 

2. Using System.arraycopy() method:

The second way to copy elements of an array to another array is by using arraycopy() method provided by the System class.


The advantage of using arraycopy() method of System class is that we can copy array the whole array into another array more quickly as a comparison to using for loop that copies array elements one by one.

Hence, this method also saves time. The general syntax to declare arraycopy() method in java is as follows:

public static void arraycopy(Object sourceArray, int srcPos, Object targetArray, int tarPos, int length);

In the above syntax:

  • sourceArray specifies the name of source array.
  • srcPos represents the starting position in the source array from where elements of the source array will be copied to the target array.
  • targetArray specifies the name of target array.
  • tarPos represents the starting position in the target array from where new elements from source array will be copied. If any array elements of target array are present at that location, it will be overridden by the elements of source array.
  • length represents the total number of elements of the source array that are to be copied into the target array.

The arraycopy() method does not allocate memory location for the target array. The target array must have already created with its memory location allocated.

After the copying takes place, targetArray and sourceArray both contain the same elements with different memory locations.

Let’s take an example program where we will copy array elements from one array into another array using arraycopy() method.

Program source code 2:

package arraysProgram;
public class CopyArrayUsingArraycopy {
public static void main(String[] args) 
{
    char[ ] sourceArray = {'D', 'H', 'A', 'N', 'B', 'A', 'D'};
// Create an array targetArray[] of same size as sourceArray[ ].
     char[ ] targetArray = new char[sourceArray.length];
// Copy array elements from sourceArray[ ] into targetArray[ ].  
     System.arraycopy(sourceArray, 0, targetArray, 0, 7);
 
 System.out.println("Elements of sourceArray[]: ");
 for (int i = 0; i < sourceArray.length; i++)
     System.out.print(sourceArray[i] + " ");

 System.out.println("\n\nElements of targetArray[]: ");
 for (int i = 0; i < targetArray.length; i++)
     System.out.print(targetArray[i] + " ");
 }
}
Output:
         Elements of sourceArray[]: 
         D H A N B A D 
         Elements of targetArray[]: 
         D H A N B A D 

In this program, two characters type arrays named sourceArray and targetArray are created. The array sourceArray has been initialized with some character values while targetArray is not initialized.


After creating both arrays, we have copied elements of sourceArray into targetArray by using arraycopy() method and then display elements of both arrays using for loop.


3. Using clone() method to copy array:

Let’s take an example program where we will copy array elements from one array to another array by using clone() method.

Program source code 3:

package arraysProgram;
public class CopyArrayUsingClone {
public static void main(String[] args) 
{
    char[ ] oArray = {'D', 'H', 'A', 'N', 'B', 'A', 'D'};
// Copying char array elements from oArray[ ] into nArray[] using clone method.
     char[ ] nArray = oArray.clone();
   
 System.out.println("Elements of oArray[]: ");
 for (int i = 0; i < oArray.length; i++)
     System.out.print(oArray[i] + " ");

 System.out.println("\n\nElements of nArray[]: ");
 for (int i = 0; i < nArray.length; i++)
     System.out.print(nArray[i] + " ");
 }
}
Output:
        Elements of oArray[ ]: 
        D H A N B A D 
        Elements of nArray[ ]: 
        D H A N B A D 

4. Using copyOf() method of java.util.Arrays class:

This is the fourth approach to copy array elements from one array to another array by using copyOf() static method of Arrays class. Let’s take an example program based on it.

Program source code 4:

package arraysProgram;
import java.util.Arrays;
public class CopyArrayUsingLoop {
public static void main(String[] args) 
{
  String[ ] oArray = {"John", "Ivaan", "Amit", "Herry"};
// Copying string array elements from oArray[] into nArray[] using copyOf method.
  String[ ] nArray = Arrays.copyOf(oArray, oArray.length);
   
 System.out.println("Elements of oArray[]: ");
 for (int i = 0; i < oArray.length; i++)
     System.out.print(oArray[i] + " ");

 System.out.println("\n\nElements of nArray[]: ");
 for (int i = 0; i < nArray.length; i++)
     System.out.print(nArray[i] + " ");
 }
}
Output:
         Elements of oArray[]: 
         John Ivaan Amit Herry 
         
         Elements of nArray[]: 
         John Ivaan Amit Herry

5. Using copyOfRange method of Arrays class:

This is the last approach to copy array elements of one array into another array. This method provides a specific range to copy array elements from one array into another array.

Let’s take an example program where we will copy array elements of the specified range of specified array into the new array.

Program source code 5:

package arraysProgram;
import java.util.Arrays;
public class CopyArrayUsingCopyOfRange {
public static void main(String[] args) 
{
     int[ ] oArray = {2, 3, 4, 5, 6, 7, 8, 10};
// Copying int array elements from oArray[] into nArray[] using copyOfRange method.
     int[ ] nArray = Arrays.copyOfRange(oArray, 2, 7);
   
 System.out.println("Elements of oArray[]: ");
 for (int i = 0; i < oArray.length; i++)
     System.out.print(oArray[i] + " ");

 System.out.println("\n\nElements of nArray[]: ");
 for (int i = 0; i < nArray.length; i++)
     System.out.print(nArray[i] + " ");
 }
}
Output:
         Elements of oArray[]: 
         2 3 4 5 6 7 8 10 

         Elements of nArray[]: 
         4 5 6 7 8 

Key points:

1. We can use the assignment operator to copy primitive data type variables, but not arrays.

2. We can use for loop to copy individual elements one by one. But we can avoid iteration over elements using clone() or System.arraycopy() method.

3. clone() method creates a new array of the same size.

4. System.arraycopy() can be used to copy arrays instead of using loop or clone() method.

5. System.arraycopy() is faster than clone() and loop.

6. Arrays.copyOf() method can be used to copy the first few elements of an array or a full copy of an array.

7. Arrays.copyOfRange() is used to copy a specified range of an array.


Hope that this tutorial has covered almost all the techniques to copy array elements from one array into another. I hope that you will have understood the simple topic “array copy in Java with examples”.
Thanks for reading!!!
Next ⇒ Linear Array Search in Java⇐ Prev Next ⇒