Copy Array in Java

Array Programs in Java – 9 | In the previous Java program, we have seen how to compare two arrays in Java. Now in this post, we will see Java Array Copy | How to clone or copy array in Java? How to copy a 2D array in Java? What are the different ways to copy array in Java? Here, we will discuss all these points.

There are various in-built methods like System.arraycopy(), Arrays.copyOf(), Arrays.copyOfRange(), and clone() method which can be used to copy array in Java. We can also copy manually by assigning each element to another array element. Let us see them one by one.


Shallow Copy of Array in Java using assignment Operator (=)

We can copy array in Java by using the assignment operator (=). Let us demonstrate it through an example.

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      int arr[] = {10, 20, 30, 40, 50};
      
      // copy array using assignment operator
      int newArr[] = arr;
      
      // display array
      System.out.println("Original Array = " + Arrays.toString(arr));
      System.out.println("Copied Array = " + Arrays.toString(newArr));
   }

}

Output:-

Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

To display the array we have used toString() method which is given in java.util.Arrays class. But you can also use loops like for loop, for-each loop, and e.t.c. See:- Different ways to print/display array in Java.

It is an example of a shallow copy. In shallow copy, the reference of the array is assigned to the new array.

Limitation of this approach:- If we modify the content of the original array then the content of the newly created array will also change. The below program demonstrate this point,

// original array
int arr[] = {10, 20, 30, 40, 50};

// copy array using assignment operator
int newArr[] = arr;

// display array (Before Modification)
System.out.println("Before Modification,");
System.out.println("Original Array = " + Arrays.toString(arr));
System.out.println("Copied Array = " + Arrays.toString(newArr));

// modifying content of original array
arr[0] = 555;
arr[3] = 777;

// display array (After Modification)
System.out.println("\nAfter Modification,");
System.out.println("Original Array = " + Arrays.toString(arr));
System.out.println("Copied Array = " + Arrays.toString(newArr));

Output:-

Before Modification,
Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

After Modification,
Original Array = [555, 20, 30, 777, 50]
Copied Array = [555, 20, 30, 777, 50]

Deep Copy of Array in Java using Loops

To create a deep copy of the array in Java using loop we have to perform the following operations:-
1) Create a new array with a similar data type and size.
2) Use the loop to iterate through the original array.
3) Copy the ith element of the original array to the ith element of the new array.

Before creating a new array, first, calculate the size of the original array. The length property of the array can be used to calculate the size of an array in Java. Now, let us demonstrate the deep copy of the array using loops.

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      int arr[] = { 10, 20, 30, 40, 50 };

      // create new array with similar type and size
      int newArr[] = new int[arr.length];

      // copy using loop
      for (int i = 0; i < arr.length; i++) {
         // copy elements
         newArr[i] = arr[i];
      }

      // display array
      System.out.println("Original Array = " + Arrays.toString(arr));
      System.out.println("Copied Array = " + Arrays.toString(newArr));
   }

}

Output:-

Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

In a deep copy, each element of the original array is assigned to a new array therefore whenever we change the content of the original array then the elements of the newly created array won’t be affected.

// original array
int arr[] = { 10, 20, 30, 40, 50 };

// create new array with similar type and size
int newArr[] = new int[arr.length];

// copy using loop
for (int i = 0; i < arr.length; i++) {
   // copy elements
   newArr[i] = arr[i];
}

// display array (Before Modification)
System.out.println("Before Modification,");
System.out.println("Original Array = " + Arrays.toString(arr));
System.out.println("Copied Array = " + Arrays.toString(newArr));

// modifying content of original array
arr[0] = 555;
arr[3] = 777;

// display array (After Modification)
System.out.println("\nAfter Modification,");
System.out.println("Original Array = " + Arrays.toString(arr));
System.out.println("Copied Array = " + Arrays.toString(newArr));

Output:-

Before Modification,
Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

After Modification,
Original Array = [555, 20, 30, 777, 50]
Copied Array = [10, 20, 30, 40, 50]

Copy Array in Java using System.arraycopy()

The System.arraycopy() method in Java is given to copy an array to another array. It copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Syntax of the arraycopy() method in java.lang.System class:- public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

In this syntax,

  • src:- The source array.
  • srcPos:- Starting position in the source array.
  • dest:- The destination array.
  • destPos:- starting position in the destination data.
  • length:- the number of array elements to be copied.

Since java.lang.System class is imported by default in all Java classes therefore to use arraycopy() method no need to explicitly import the System class.

Program to copy array in Java using System.arraycopy() method

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      int arr[] = { 10, 20, 30, 40, 50 };

      // create new array with similar type and size
      int newArr[] = new int[arr.length];

      // copy array using System.arraycopy
      System.arraycopy(arr, 0, newArr, 0, arr.length);

      System.out.println("Original Array = " + Arrays.toString(arr));
      System.out.println("Copied Array = " + Arrays.toString(newArr));
   }

}

Output:-

Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

It performs a shallow copy of the array. It means when arraycopy() is applied to non-primitive arrays then it copies Object references rather than object data.

In its respective post of System.arraycopy() method, we already verified this point through the 2D array and using an array of objects. Again in this post, we will see it while discussing the copy of 2D array.

Note:- The arraycopy() is likely the fastest way to copy an array, and it gives better performance compared to normal array copy using loops. It’s in the system because it uses a direct memory copy outside of Java land. The java.lang.System class provides useful methods for standard input and output, for loading files and libraries, or to access externally defined properties.

Copy array in Java using Arrays.copyOf() Method

The copyOf() method of java.util.Arrays class in Java copies the specified array, truncating or padding with zeros/nulls (if necessary). Internally, this method calls the System.arraycopy() method.

There is a total of 10 overloaded forms of Arrays.copyOf() method. Some of them are given below. The remaining overloaded forms of Arrays.copyOf() method is implemented in a similar way. The copyOf() method with all its overloaded forms was introduced in Java 1.6 version.

  • public static int[] copyOf(int[] original, int newLength)
  • public static <T> T[] copyOf(T[] original, int newLength)

In these methods the parameters are,

  • original:- The array to be copied.
  • newLength:- The length of the copy to be returned.

Program to copy array in Java using Arrays.copyOf() Method,

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      int arr[] = { 10, 20, 30, 40, 50 };

      // copy array using Arrays.copyOf()
      int[] newArr = Arrays.copyOf(arr, arr.length);

      System.out.println("Original Array = " + Arrays.toString(arr));
      System.out.println("Copied Array = " + Arrays.toString(newArr));
   }

}

Output:-

Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

Additional Points,

  • This method throws NullPointerException if the passed original array is null. Therefore, it is better to check if(original != null) and then call copyOf().
  • It also throws NegativeArraySizeException if the passed length (i.e. newLength) is negative.

Since Arrays.copyOf() method internally using System.arraycopy() therefore it is also performing shallow copy.

Copy array in Java using Arrays.copyOfRange() Method

Similar to Arrays.copyOf() method we can also use Arrays.copyOfRange() method. Both the methods are very similar, and copyOfRange() method performs copy operation only within the specified range. Similar to the copyOf() method internally it is also using System.arraycopy() method, and performs the shallow copy. There are many overloaded forms of this method,

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

In this method the parameters are,

  • original:- The array from which a range is to be copied.
  • from:- The initial index of the range to be copied, it is inclusive.
  • to:- the final index of the range to be copied, exclusive. This index may lie outside the array.

The copyOfRange() method returns a new array containing the specified range from the original array, truncated or padded with zeros to obtain the required length. Let us demonstrate it through an example.

Program to copy array in Java using Arrays.copyOfRange() Method

// original array
int arr[] = { 10, 20, 30, 40, 50 };

// copy array 
int[] newArr = Arrays.copyOfRange(arr, 0, arr.length);

System.out.println("Original Array = " + Arrays.toString(arr));
System.out.println("Copied Array = " + Arrays.toString(newArr));

Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

Java Array Clone

We can also perform array copy in Java using the clone() method of java.lang.Object class. The clone() method of java.lang.Object class performs a shallow copy. It means when clone() is applied to non-primitive arrays then it copies Object references rather than object data. Let us demonstrate it through an example,

Copy array in Java using clone() method

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      int arr[] = { 10, 20, 30, 40, 50 };

      // copy array using clone()
      int[] newArr = arr.clone();
       
      // display array (Before Modification)
      System.out.println("Before Modification,");
      System.out.println("Original Array = " + Arrays.toString(arr));
      System.out.println("Copied Array = " + Arrays.toString(newArr));

      // modifying content of original array
      arr[0] = 555;
      arr[3] = 777;

      // display array (After Modification)
      System.out.println("\nAfter Modification,"); 
      System.out.println("Original Array = " + Arrays.toString(arr));
      System.out.println("Copied Array = " + Arrays.toString(newArr));
   }

}

Output:-

Before Modification,
Original Array = [10, 20, 30, 40, 50]
Copied Array = [10, 20, 30, 40, 50]

After Modification,
Original Array = [555, 20, 30, 777, 50]
Copied Array = [10, 20, 30, 40, 50]

More Example

All the previous examples use int type array. Let us see an example of a different type of array. Here, we will demonstrate System.arraycopy(), Arrays.copyOf(), Arrays.copyOfRange() method in single example. To demonstrate each method, uncomment it and comment remaining two approaches.

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      String str[] = {"Java", "Python", "C++"};

      // copy array using System.arraycopy()
      String[] newArr = new String[str.length];
      System.arraycopy(str, 0, newArr, 0, str.length);
      
      // copy using Arrays.copyOf()
      // String[] newArr = Arrays.copyOf(str, str.length);
      
      // copy using clone()
      // String[] newArr = str.clone();
      
      // display array (Before Modification)
      System.out.println("Before Modification,");
      System.out.println("Original Array = " + Arrays.toString(str));
      System.out.println("Copied Array = " + Arrays.toString(newArr));

      // modifying content of original array
      str[0] = "C#";
      str[2] = "HTML";

      // display array (After Modification)
      System.out.println("\nAfter Modification,"); 
      System.out.println("Original Array = " + Arrays.toString(str));
      System.out.println("Copied Array = " + Arrays.toString(newArr));
   }

}

Output:-

Before Modification,
Original Array = [Java, Python, C++]
Copied Array = [Java, Python, C++]

After Modification,
Original Array = [C#, Python, HTML]
Copied Array = [Java, Python, C++]


Copy 2D Array in Java

In all the previous examples, we were copying the single-dimensional array. Now, let us see different approaches to copy the multidimensional array in Java. We will demonstrate all these points through a two-dimensional array.

Shallow Copy of 2D Array in Java

Java Program to copy two-dimensional (2D) array in Java using System.arraycopy() method,

import java.util.Arrays;

public class CopyArray {
   public static void main(String[] args) {

      // original 2D array 3x2
      int src[][] = { { 1, 2 }, { 4, 5 }, { 7, 8 } };

      // destination array
      int dest[][] = new int[3][2];

      // copy array using System.arraycopy
      System.arraycopy(src, 0, dest, 0, src.length);

      // display both array
      System.out.println("Source array = " + Arrays.deepToString(src));
      System.out.println("Destination array = " 
                             + Arrays.deepToString(dest) );

   }
}

Output:-

Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

Java Program to copy two-dimensional 2D array in Java using Arrays.copyOf() method,

// original 2D array 3x2
int src[][] = { { 1, 2 }, { 4, 5 }, { 7, 8 } };

// copy array using Arrays.copyOf()
int dest[][] = Arrays.copyOf(src, src.length);

// display both array
System.out.println("Source array = " + Arrays.deepToString(src));
System.out.println("Destination array ="+Arrays.deepToString(dest));

Output:-

Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

Java program to copy two-dimensional 2D array in Java using Arrays.copyOfRange() method,

// original 2D array 3x2
int src[][] = { { 1, 2 }, { 4, 5 }, { 7, 8 } };

// copy array 
int dest[][] = Arrays.copyOfRange(src, 0, src.length);

// display both array
System.out.println("Source array = " + Arrays.deepToString(src));
System.out.println("Destination array = "+Arrays.deepToString(dest));

Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

Java Program to copy two-dimensional 2D array in Java using clone() method,

// 2D array 3x2
int src[][] = { { 1, 2 }, { 4, 5 }, { 7, 8 } };

// copy array using clone()
int dest[][] = src.clone();

// display array
System.out.println("Source array = " + Arrays.deepToString(src));
System.out.println("Destination array = " + Arrays.deepToString(dest));

Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

Limitations of These Approaches

The System.arraycopy(), Arrays.copyOf(), Arrays.copyOfRange(), and clone() methods are performing shallow copy, which can create several problems. Let us demonstrate it through an example:-

import java.util.Arrays;

public class CopyArray {

   public static void main(String[] args) {
      // original array
      int src[][] = { { 1, 2 }, { 4, 5 }, { 7, 8 } };
      
      // copy array using System.arraycopy()
      int dest[][] = new int[3][2];
      System.arraycopy(src, 0, dest, 0, src.length);
      
      // copy array using Arrays.copyOf()
      // int dest[][] = Arrays.copyOf(src, src.length);
      
      // copy array using clone()
      // int dest[][] = src.clone();

      // display array (Before Modification)
      System.out.println("Before Modification,");
      System.out.println("Source array = " + Arrays.deepToString(src));
      System.out.println("Destination array = " 
                        + Arrays.deepToString(dest));

      // modify original array
      src[0][0] = 999;
      src[1][1] = 888;

      // display array (After Modification)
      System.out.println("\nAfter Modification,");
      System.out.println("Source array = " + Arrays.deepToString(src));
      System.out.println("Destination array = " 
                        + Arrays.deepToString(dest));
   }
}

Output:-

Before Modification,
Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

After Modification,
Source array = [[999, 2], [4, 888], [7, 8]]
Destination array = [[999, 2], [4, 888], [7, 8]]

Deep Copy of 2D Array in Java

We can perform deep copy using loops. To do this iterate through the multi-dimensional array and copy each element to the new array. Let us see it through an example. In this program, we will write logic to copy an array inside the method. See:- How to find size/length of 2D array

import java.util.Arrays;

public class CopyArray {

   // copy multidimensional array using loop (deep copy)
   public static int[][] copy(int[][] src) {
      // create 2D array and assign size of parent array
      int temp[][] = new int[src.length][];

      for (int i = 0; i < src.length; i++) {
         // assign size of child array
         temp[i] = new int[src[i].length];

         for (int j = 0; j < src[i].length; j++) {
            // copy element
            temp[i][j] = src[i][j];
         }
      }

      // return
      return temp;
   }

   public static void main(String[] args) {

      // original 2D array 3x2
      int src[][] = { { 1, 2 }, { 4, 5 }, { 7, 8 } };

      // copy array using Arrays.copyOf()
      int dest[][] = copy(src);

      // display both array
      System.out.println("Source array = " + Arrays.deepToString(src));
      System.out.println("Destination array = " 
                    + Arrays.deepToString(dest));

      // modify original array
      src[0][0] = 999;
      src[1][1] = 888;

      // display array (After Modification)
      System.out.println("\nAfter Modification,");
      System.out.println("Source array = " + Arrays.deepToString(src));
      System.out.println("Destination array = " 
                    + Arrays.deepToString(dest));

   }

}

Output:-

Before Modification,
Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

After Modification,
Source array = [[999, 2], [4, 888], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

Since we are taking the example of a 2D array of integer numbers, therefore we can also take the help of System.arraycopy(), Arrays.copyOf() and Arrays.copyOfRange() method to copy 1D array.

Note that these methods are performing shallow copy only when the given array is non-primitive. It means when these methods are applied to non-primitive arrays then only it copies Object references rather than object data. But matrix or our 2D array in this example contains an array of int values at second dimension. Therefore we can use them as follows:-

// copy multidimensional array (deep copy)
public static int[][] copy(int[][] src) {
      
   // create 2D array and assign size of parent array
   int temp[][] = new int[src.length][];

   for (int i = 0; i < src.length; i++) {
      // copy second dimensional array
      temp[i] = Arrays.copyOf(src[i], src[i].length); 
   }

   // return
   return temp;
}

Replace this method with the previous method. The output for this time,

Before Modification,
Source array = [[1, 2], [4, 5], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

After Modification,
Source array = [[999, 2], [4, 888], [7, 8]]
Destination array = [[1, 2], [4, 5], [7, 8]]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *