java add two arrays together

ht‮ww//:spt‬w.lautturi.com
java add two arrays together

To add two arrays together in Java, you can use the System.arraycopy method of the java.lang package to copy the elements of one array into another array.

Here is an example of how you can add two arrays together in Java:

int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};

// Create a new array that is the sum of the two arrays
int[] sum = new int[arr1.length + arr2.length];

// Copy the elements of arr1 into sum
System.arraycopy(arr1, 0, sum, 0, arr1.length);

// Copy the elements of arr2 into sum
System.arraycopy(arr2, 0, sum, arr1.length, arr2.length);

// Print the sum array
System.out.println(Arrays.toString(sum));  // Output: [1, 2, 3, 4, 5, 6]

In this example, the arr1 and arr2 variables are integer arrays with three elements each.

The sum array is created as a new array with the length equal to the sum of the lengths of the two arrays.

The System.arraycopy method is used to copy the elements of arr1 into the sum array, starting at the index 0 of the sum array.

Then, the System.arraycopy method is used again to copy the elements of arr2 into the sum array, starting at the index equal to the length of arr1.

Finally, the Arrays.toString method is used to print the elements of the sum array.

It is important to note that the System.arraycopy method is a native method, and it is called using the System class name, not an instance of the System class.

Additionally, the System.arraycopy method is a varargs method, which means that it can accept a variable number of arguments.

Therefore, you can use the System.arraycopy method to copy a variable number of elements from one array to another array.

For example:

System.arraycopy(arr1, 1, sum, 3, 2);

This copies two elements from the arr1 array, starting at the index 1, into the sum array, starting at the index 3.

It is also possible to use the ArrayUtils.addAll method of the org.apache.commons.lang3.ArrayUtils class to add two arrays together in Java.

The ArrayUtils.addAll method takes two arrays as arguments, and it returns a new array that is the concatenation of the two arrays.

Here is an example of how you can use the ArrayUtils.addAll method to add two arrays together in Java:

import org.apache.commons.lang3.ArrayUtils;

public static void main(String[] args) {
    int[] arr1 = { 1,2,3,4,5};
    int[] arr2 = { 6,7,8,9,10 };
    int[] combinedArr = ArrayUtils.addAll(arr1, arr2);
    System.out.println(Arrays.toString(combinedArr));
}
Created Time:2017-11-01 22:29:55  Author:lautturi