In this java program tutorial, we will write a program to merge two arrays in java. Before that, you may go through the following topic in java.
Explanation: In merge programming in C, we will take two arrays and merge them in a third array. We will take user input for the size of an array and elements of an array for both arrays. The final element is stored in a mergeArray[].
Java Program to Merge Two Arrays
Source Code: Program to merge arrays in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import java.util.Scanner; public class Main { public static void main(String args[]) { int size1, size2, size, i, j, k; int arr1[] = new int[50]; int arr2[] = new int[50]; int mergeArray[] = new int[100]; Scanner scan = new Scanner(System.in); System.out.print("Enter the size of a first array: "); size1 = scan.nextInt(); System.out.println("Enter " + size1 + " elements in first Array:"); for (i = 0; i < size1; i++) arr1[i] = scan.nextInt(); System.out.print("Enter the size of a second array: "); size2 = scan.nextInt(); System.out.println("Enter " + size2 + " elements in Second Array:"); for (i = 0; i < size2; i++) arr2[i] = scan.nextInt(); //merging... for (i = 0; i < size1; i++) mergeArray[i] = arr1[i]; size = size1 + size2; for (i = 0, k = size1; k < size && i < size2; i++, k++) mergeArray[k] = arr2[i]; System.out.println("After Merging, the array becomes:"); for (i = 0; i < size; i++) System.out.print(mergeArray[i] + " "); } } |
Output:
Enter the size of a first array: 4
Enter 4 elements in first Array:
10
20
30
40
Enter the size of a second array: 3
Enter 3 elements in Second Array:
70
80
90
After Merging, the array becomes:
10 20 30 40 70 80 90