How to copy two arrays with System.ArrayCopy in java

Answer: Here is the script to copy two arrays in to a single resulting array

public class ArrayCopy {
public static void main(String[] args) {
// Source arrays
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6}

// Combined array to hold elements of both
int[] result = new int[array1.length + array2.length];

// Copy first array into result
System.arraycopy(array1, 0, result, 0, array1.length);

// Copy second array into result
System.arraycopy(array2, 0, result, array1.length, array2.length);

// Print the result
for (int value : result) {
System.out.print(value + ” “);
}
}

}

Explanation: In this script, we initialize two arrays arr1 and arr2 with values. We then create a new array result whose length is the combined length of arr1 and arr2. The goal is to copy both arrays into the result array using the System.arraycopy() method.

To copy arr1 into the beginning of the result array, we use the following code:

System.arraycopy(array1, 0, result, 0, array1.length);

Explanation of System.arraycopy()

The method signature is:

public static native void arraycopy(
Object src, // Source array
int srcPos, // Starting position in the source array
Object dest, // Destination array
int destPos, // Starting position in the destination array
int length // Number of elements to copy
);

According to the parameters:

  • We are copying from the source array arr1, starting at index 0.
  • We are copying into the result array, also starting at index 0.
  • The number of elements to copy is arr1.length.

Next, we copy the contents of arr2 into the result array. Since arr1 has already occupied the beginning portion of result, we start copying arr2 from the index arr1.length in the destination:

System.arraycopy(arr2, 0, result, arr1.length, arr2.length);

Here:

  • The source array is arr2, starting from index 0.
  • The destination is result, starting from index arr1.length.
  • The number of elements to copy is arr2.length.

This way, the result array will contain all elements from both arr1 and arr2, in order.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x