Home » Java programs » Java array programs

Java program to merge two one dimensional arrays



In this java program, we are going to learn how to merge two one dimensional arrays? Here, we are reading two one dimensional arrays and merging their elements.
Submitted by IncludeHelp, on December 07, 2017

Given two one-dimensional arrays and we have to merge them using java program.

Example:

Input:
Array 1 (elements will be read in program): 1 2 3 4 5 6 7 8 9 10
Array 2 (elements will be read in program): 11 12 13 14 15
Output:
New array (After merging elements)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Program to merge two one-dimensional array elements in java

import java.util.Scanner;

public class ExArrayMerge
{
   public static void main(String args[])
   {
	   // initialize the required array.
       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.in);
	   
       // enter size and elements of first array.
       System.out.print("Enter size of the first array : ");
       size1 = scan.nextInt();
	   
       System.out.println("Enter elements of the first array : ");
       for(i=0; i<size1; i++)
       {
           arr1[i] = scan.nextInt();
       }
	   
       // enter size and elements of second array.
       System.out.print("Enter size of the second array : ");
       size2 = scan.nextInt();
	   
       System.out.println("Enter elements of the second array : ");
       for(i=0; i<size2; i++)
       {
           arr2[i] = scan.nextInt();
       }
	   
       // merge both the array.
       System.out.print("Merging both 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];
       }
	   
       // new array after merging.
       System.out.print("New array after merging is :\n");
       for(i=0; i<size; i++)
       {
           System.out.print(merge[i] + "  ");
       }
   }
}

Output

Enter size of the first array : 10
Enter elements of the first array : 
1
2
3
4
5
6
7
8
9
10
Enter size of the second array : 5
Enter elements of the second array : 
11
12
13
14
15
Merging both the Arrays...
New array after merging is :
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.