Merging two arrays in java


☞We can merge two arrays and form the third array. This process is also called concatenating two arrays.

Example

import java.util.*;
class MergeArray{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
            
        int arr1[]=new int[4];
        int arr2[]=new int[3];
        int arr3[]=new int[7];
        
        int i,j;
        
        /*inputting elements in an array1*/
        System.out.println("Enter the elements of array 1");
        for(i=0;i<arr1.length;i++)
            arr1[i]=sc.nextInt();

        /*inputting elements in an array2*/
        System.out.println("Enter the elements of array 2");
        for(i=0;i<arr2.length;i++)
            arr2[i]=sc.nextInt();
        
        /*logic of merging*/
        for(i=0;i<arr1.length;i++){
            arr3[i]=arr1[i];
        }
            
        for(i=0;i<arr2.length;i++){
            arr3[arr1.length+i]=arr2[i];
        }

        /*Printing elements after merging*/
        System.out.println("After merging elements are : ");
        for(i=0;i<arr3.length;i++)
            System.out.print(arr[i]+" ");
            
    }
}

Output

Enter the elements of array 1
74
47
84
34
Enter the elements of array 2
10
20
30
After merging elements are :
74 47 84 34 10 20 30