Java Program to Concatenate Two Arrays

In this java program, we will learn about how to concatenate or merge two arrays and store the result in third array. Here we will discuss about concatenating arrays with and without using pre-defined library methods.

For Example: 
Input: array1 = {1, 2, 3, 4}, array2 = {5, 6, 7, 8}
Output: array3 = {1, 2, 3, 4, 5, 6, 7, 8}

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Concatenate Two Arrays using arraycopy() Method

Here are the steps to concatenate two arrays using arraycopy() method.
  • Given two arrays(array1 and array2) to concatenate, we will calculate the length of arrays array1 and array1 and will store it into the variables lets say Len1 and Len2. Calculating the array's length is necessary since it allows us to forecast the size of the final array using the length of these arrays.

  • Then, we create third integer array of length Len1 + Len2.

  • The two arrays are then concatenated using System.arraycopy() method, and the outcome is placed in the third array.
import java.util.Arrays;

public class ConcatenateArrays {
  public static void main(String[] args) {
    int[] array1 = {1, 2, 3, 4};
    int[] array2 = {5, 6, 7, 8};

    int Len1 = array1.length;
    int Len2 = array2.length;
    int[] result = new int[Len1 + Len2];

    System.arraycopy(array1, 0, result, 0, Len1);
    System.arraycopy(array2, 0, result, Len1, Len2);

    System.out.println(Arrays.toString(result));
  }
}
Output
[1, 2, 3, 4, 5, 6, 7, 8]

Java Program to Concatenate Two Arrays Without using Predefined Method

Here are the steps to concatenate two arrays without using any pre-defined method.
  • Given two arrays(array1 and array2) to concatenate, we will calculate the length of arrays array1 and array1 and will store it into the variables lets say Len1 and Len2. Calculating the array's length is necessary since it allows us to forecast the size of the final array using the length of these arrays.

  • Then, we create third integer array of length Len1 + Len2.

  • One by one, the items of the first array are added to the third array using the first for-loop, and similarly, the elements of the second array are added to the third array using the second for-loop.

  • The items of the third array are printed using Arrays.toString() method.
import java.util.Arrays;

public class ConcatenateArraysLoops {
  public static void main(String[] args) {
    int[] array1 = {1, 2, 3, 4};
    int[] array2 = {5, 6, 7, 8};

    int Len1 = array1.length;
    int Len2 = array2.length;
    int[] result = new int[Len1 + Len2];

    int index = 0;
    for (int num : array1) {
      result[index] = num;
      index++;
    }

    for (int num : array2) {
      result[index] = num;
      index++;
    }

    System.out.println(Arrays.toString(result));
  }
}
Output
[1, 2, 3, 4, 5, 6, 7, 8]