Java Program to Merge Two Arrays

« Previous Program Next Program »

Merge Two Arrays in Java

To merge two arrays in Java programming, you have to ask to the user to enter the first array size and then ask to enter the first array elements. Ask the same for the second array. Now initialize all the elements of the first and second array to the third array say merge[ ] and at last print the value of the third array i.e., merge[ ] as shown in the following program.

Java Programming Code to Merge Two Arrays

Following Java Program ask to the user to enter the both the array to merge and display the merged array on the screen (Here we display the direct merged array). You can also sort the two array before merge to merge these array in sorted order. So to learn about sorting, you can use one of the following three techniques to sort an array :

/* Java Program Example - Merge Two Arrays */

import java.util.Scanner;

public class JavaProgram
   public static void main(String args[])
       int size1, size2, size, i, j, k;
       int arr1[] = new int[50];
       int arr2[] = new int[50];
       int merge[] = new int[100];
       Scanner scan = new Scanner(;
       System.out.print("Enter Array 1 Size : ");
       size1 = scan.nextInt();
       System.out.print("Enter Array 1 Elements : ");
       for(i=0; i<size1; i++)
           arr1[i] = scan.nextInt();
       System.out.print("Enter Array 2 Size : ");
       size2 = scan.nextInt();
       System.out.print("Enter Array 2 Elements : ");
       for(i=0; i<size2; i++)
           arr2[i] = scan.nextInt();
       System.out.print("Merging the Arrays...\n");
       for(i=0; i<size1; i++)
           merge[i] = arr1[i];
       size = size1 + size2;
       for(i=0, k=size1; k<size && i<size2; i++, k++)
           merge[k] = arr2[i];
       System.out.print("Now the New Array after Merging is :\n");
       for(i=0; i<size; i++)
           System.out.print(merge[i] + "  ");

When the above Java Program is compile and executed, it will produce the following output:

Java Program merge two array

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

« Previous Program Next Program »

Latest 5 Posts by CodesCracker


Quick Links
Signup - Login - Give Online Test