Merge Array Program in Java

Merge Array Program in Java
Merge Array Program in Java

import java.util.Scanner;

public class MergeArray
{
    public static void main(String[] args)
    {
        int ar1[] = new int[10];
        int ar2[] = new int[10];
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first array:");
        for (int i = 0; i < 10; i++)
        {
            System.out.print("Enter the number ar1[" + i + "]:");
            ar1[i] = sc.nextInt();
        }
        System.out.println("Enter second array:");
        for (int i = 0; i < 10; i++)
        {
            System.out.print("Enter the number ar2[" + i + "]:");
            ar2[i] = sc.nextInt();
        }
        
        int totalLength = ar1.length + ar2.length;
        int idx=0;
        int ar3[] = new int[totalLength];
        for (int i = 0; i < ar1.length; i++)
        {
            ar3[i] = ar1[i];
            idx++;
        }
        for (int j = 0; j < ar2.length; j++)
        {
            ar3[idx++] = ar2[j];
        }
        
        System.out.println("Merged array:");
        for (int i = 0; i < totalLength; i++)
        {
            System.out.println("ar3[" + i + "]:" + ar3[i]);
        }
    }
}

Output:

Enter first array:
Enter the number ar1[0]:1
Enter the number ar1[1]:2
Enter the number ar1[2]:3
Enter the number ar1[3]:4
Enter the number ar1[4]:5
Enter the number ar1[5]:6
Enter the number ar1[6]:7
Enter the number ar1[7]:8
Enter the number ar1[8]:9
Enter the number ar1[9]:10
Enter second array:
Enter the number ar2[0]:11
Enter the number ar2[1]:22
Enter the number ar2[2]:33
Enter the number ar2[3]:44
Enter the number ar2[4]:55
Enter the number ar2[5]:66
Enter the number ar2[6]:77
Enter the number ar2[7]:88
Enter the number ar2[8]:99
Enter the number ar2[9]:110
Merged array:
ar3[0]:1
ar3[1]:2
ar3[2]:3
ar3[3]:4
ar3[4]:5
ar3[5]:6
ar3[6]:7
ar3[7]:8
ar3[8]:9
ar3[9]:10
ar3[10]:11
ar3[11]:22
ar3[12]:33
ar3[13]:44
ar3[14]:55
ar3[15]:66
ar3[16]:77
ar3[17]:88
ar3[18]:99
ar3[19]:110
icse java java tutorials learn java programs