How Can I Concatenate Two Arrays In Java?

Here we will learn How Can I Concatenate Two arrays In java? which we can perform in two ways one by using arraycopy and another by simply iterating both the array and simply storing all the elements in another third array.

Concatenate Two Arrays In Java

Ways To Concatenate Two Array In Java

There are two ways to concatenate two arrays in java, Let’s discuss both methods in detail.

Using arraycopy

It is a way to add two arrays or we can say concatenate two arrays lets understand with an example here.

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));
    }
}

We can see how array1 and array2 are being concatenated by in build function arraycopy and both the arrays are stored in a third array called result as of the above result.

Without arraycopy

We can also concatenate without using any in-build function or we can say simply by iterating each element and storing them in a third array one by one. With the complexity of O(mn).

For more understanding let’s follow the example given below

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));
    }
}

Here we can see how both arrays are concatenated one by one.

Learn More about How Can I Concatenate Two Arrays In Java? at: Concatenate array

And also Visit Java Tutorials to learn more and solve the problems faced related to java also visit Python’s list: What is the difference Between methods Append and Extend? to learn more about other topics related to python’s different other programming problems.

Leave a Comment

%d bloggers like this: