English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to concatenate two arrays in Java using and not using arraycopy.
import java.util.Arrays; public class Concat { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int aLen = array1.length; int bLen = array2.length; int[] result = new int[aLen + bLen]; System.arraycopy(array1, 0, result, 0, aLen); System.arraycopy(array2, 0, result, aLen, bLen); System.out.println(Arrays.toString(result)); } }
When the program is run, the output is:
[1, 2, 3, 4, 5, 6]
In the above program, we have two integer arrays array1and array2.
To merge (concatenate) two arrays, we store their lengths in aLen and bLen separately. Then, we create a new integer array with a length of aLen + bLen's new integer array result.
Now, to combine them, we use the arraycopy() function to copy each element from both arrays to the result.
function arraycopy(array1, 0, result, 0, aLen) simply tells the program to start copying array1Copy to the result starting from index 0.
Similarly, arraycopy(array2, 0, result, aLen, bLen) tells the program to start copying array2Copy to the result, from index aLen to bLen.
import java.util.Arrays; public class Concat { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int length = array1.length + array2.length; int[] result = new int[length]; int pos = 0; for (int element : array1) { result[pos] = element; pos++; } for (int element : array2) { result[pos] = element; pos++; } System.out.println(Arrays.toString(result)); } }
When the program is run, the output is:
[1, 2, 3, 4, 5, 6]
In the above program, we did not use arraycopy but manually copied the array array1and array2each element to result.
We store the total number of lengths needed for result, which is the length of array1.length + array2. length. Then, we create a new length array result.
Now, we use for-each loop through array1each element of it and store it in the result. After allocation, we increase the position pos1, pos ++.
Similarly, we operate on array2Perform the same operation and start from array1Start storing each element of result from the position.