OneBite.Dev - Coding blog in a bite size

copy an array in java

Code snippet on how to copy an array in java

int[] arr1 = {1,2,3,4};
    
int[] arr2 = new int[arr1.length];
    
System.arraycopy(arr1, 0, arr2, 0, arr1.length);

This code will copy the elements of one array (arr1) to another array (arr2). First, the code declares an array called arr1 with four elements, 1, 2, 3, and 4. Next, it declares an empty array called arr2 with a length equal to arr1. Finally, it uses System.arraycopy to copy arr1 to arr2. The System.arraycopy arguments are the source array (arr1), the starting index of the source array (0), the target array (arr2), the starting index of the target array (0) and the length of the source array (arr.length). At the end, arr2 will contain the same elements as arr1, in the same order.

java