Concatenate Two Arrays using Java

thumbnail

In this tutorial, you will learn about concatenate two arrays using arraycopy function and without it. We will create two integer arrays with name array1 and array2. We have to find the length each arrays stored in aLen and bLen, respectively. Then, we create a new integer array result with length aLen + bLen. Now, in order to combine to both, we copy each elements in both arrays to result by using arraycopy() function. The arraycopy(array1, 0, result, 0 ,aLen) fucntion tells the program to copy array1 starting from index 0 to result from index 0 to aLen. Likewise, for arraycopy(array2, 0, result, aLen, bLen) tells the program to copy array2 starting from index 0 to result 0 from index aLen to bLen.

Example 1: Concatenate Two Arrays using arraycopy function in Java

import java.util.Arrays;

public class Example1 {
    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));
    }
}

The output will be:

[1, 2, 3, 4, 5, 6]

In the next example, we will show to you the code to concatenate two arrays without arraycopy function. We will manually copy each element of both arrays that is array1 and array2 to result. We need to store the total length (array1.length+array2.length) from the two arrays into variable length because it required for the result variable. Then, we will be able to create a new array result of the length.

Example 2: Concatenate Two Arryas without using arraycopy function in Java

import java.util.Arrays;

public class Example2 {
    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));
    }
}

The output will be:

[1, 2, 3, 4, 5, 6]
Back To Top