In this tutorial you will learn about the Java Program to Merge Two Arrays and its application with practical example.
Java Program to Merge Two Arrays
In this tutorial, we will learn to create a Java program that will Merge Two Arrays using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operations in Java Programming.
What is Merging?
The merging means is adding two or more arrays into one. Merging can be done with a simple Java programming code.
Merging Two Arrays.
In this program, First, we will declare arrays one and two for the program. Then we will find the combined length for the merged array. After that, we will merge both the array. Then we will print the elements of the merged array to the user with the help of the print function.
With the help of this program, we can merge Two Arrays in an Array.
Program Code:-
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 41 42 43 44 |
// Java Program to demonstrate merging // two array using pre-defined method import java.util.Arrays; public class Merge2Array { //Body of the main function. public static void main(String[] args) { // Declaring the variables for the program. // first array. int[] x = { 10, 20, 30, 40 }; // second array. int[] y = { 50, 60, 70, 80 }; // determines length of firstArray. int arry1 = x.length; // determines length of secondArray int arry2 = y.length; // resultant array size int arrymerged = arry1 + arry2; // create the resultant array int[] z = new int[arrymerged]; // using the pre-defined function arraycopy System.arraycopy(x, 0, z, 0, arry1); System.arraycopy(y, 0, z, arry1, arry2); // prints the resultant array //Printing the array 1 System.out.println("Array 1 = "); System.out.println(Arrays.toString(x)); //Printing the array 2 System.out.println("Array 2 = "); System.out.println(Arrays.toString(y)); //Printing the merged array System.out.println("merged array = "); System.out.println(Arrays.toString(z)); } } |
Output:-
In the above program, we have first initialized the required variable.
- x = it will hold the integer value.
- y = it will hold the integer value.
- z = it will hold the integer value.
Finding the size of the arrays.
Program Code to Merge Two Arrays.
Printing output of the program.