merge two array in java code example

Example 1: concatenate two arrays in java

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

Example 2: combine two array in java

public static void main(String[] args) {

// for each ile cozumu
        String[] arr3 = {"A", "B", "C","Z","N"};
        String[] arr4 = {"D", "E", "F","G","U"};

ArrayList<String> list1 = new ArrayList<>(); 
  //[A, B, C, Z, N, D, E, F, G, U]

        for( String each: arr3 ){
            list1.add( each );
        }
        for(String each1 : arr4  ){
            list1.add(each1);
        }
        System.out.println(list1); // [A, B, C, Z, N, D, E, F, G, U]
    }

Tags:

Java Example