DEV Community

Cover image for How to Copy Array in Java
Emmanuel Ogbinaka
Emmanuel Ogbinaka

Posted on

How to Copy Array in Java

So you have two arrays A and B, and you need to copy the elements of A into B. Well there are various ways you can do this in Java and in this post I'll be showing you a couple of ways you can.

Method One : ForLoop
This good old for-loop to the rescue:

int[] A = {1,2,4,4};
int[] B = new int[];

 for (int i = 0; i < A.length; i++){
      B[i] = A[i];
}
Enter fullscreen mode Exit fullscreen mode

Method Two : .clone()
The clone method of array can help you simply achieve this.

Usage
int[] A = {1,2,4,4};
int[] B = A.clone();//the clone method copies the content of A into B;
Enter fullscreen mode Exit fullscreen mode

Method Three : System.arraycopy()
The next option is to use System.arraycopy() method present in the java.lang package. Before we get into it's usage, let's discuss it's signature:

public static void arraycopy(
    Object src, //:source array, in this case A
    int srcPos, //:the start index for copy, typically 0
    Object dest, //:destination object in this case B. 
    int destPos, //:the index to place the copied elements
    int length //:the length of the contents to be copied
);
Enter fullscreen mode Exit fullscreen mode
Usage
int[] A = {1,2,4,4};
int[] B = new int[];

System.arraycopy(A, 0, B, 0, A.length);
Enter fullscreen mode Exit fullscreen mode

Method Four : Arrays.copyOf()
The next option we'll be discussing is from the Arrays class present in the java.utils package. Once again, let's discuss it's signature:

public static int[] copyOf( 
    int[] original, // :source array in this case A
    int newLength // :the length of the contents to be copied
);
Enter fullscreen mode Exit fullscreen mode
Usage
int[] A = {1,2,4,4};
int[] B = Arrays.copyOf(A, 3);
Enter fullscreen mode Exit fullscreen mode

Method Five : Arrays.copyOfRange()
So, this will be the last option we'll be discussing for this post and from the Arrays class present in the java.utils package. Once again, let's see it's signature:

public static int[] copyOfRange​(
    int[] original, // :source array in this case A
    int from,  //:the start index for copy, typically 0
    int to // the end index exclusive
);
Enter fullscreen mode Exit fullscreen mode
Usage
int[] A = {1,2,3,4,5,6,7};
int[] B = Arrays.copyOfRange(A, 0, A.length);
Enter fullscreen mode Exit fullscreen mode

Discussion (0)