1. Introduction
Merging two arrays involves creating a new array and filling it with elements from the given two arrays consecutively. This Java program demonstrates how to merge two arrays into a single array.
2. Program Steps
1. Define a class named MergeArrays.
2. Inside the main method:
a. Initialize two integer arrays, array1 and array2, with some elements.
b. Calculate the length of the merged array, which is the sum of the lengths of array1 and array2.
c. Create a new integer array, mergedArray, with the calculated length.
d. Use two for loops to fill the mergedArray first with elements of array1 and then with elements of array2.
e. Print the mergedArray.
3. Code Program
public class MergeArrays { // Step 1: Define a class named MergeArrays
public static void main(String[] args) { // Main method
int[] array1 = {1, 2, 3}; // Step 2a: Initialize array1 with elements 1, 2, 3
int[] array2 = {4, 5, 6}; // Step 2a: Initialize array2 with elements 4, 5, 6
int length = array1.length + array2.length; // Step 2b: Calculate the length of mergedArray
int[] mergedArray = new int[length]; // Step 2c: Create a new array mergedArray with the calculated length
// Step 2d: Fill the mergedArray with elements of array1 and array2
for(int i = 0; i < array1.length; i++) {
mergedArray[i] = array1[i];
}
for(int i = 0; i < array2.length; i++) {
mergedArray[i + array1.length] = array2[i];
}
// Step 2e: Print the mergedArray
for(int i : mergedArray) {
System.out.print(i + " ");
}
}
}
Output:
1 2 3 4 5 6
4. Step By Step Explanation
– Step 1: A class named MergeArrays is defined.
– Step 2a: Inside the main method, we initialize two arrays array1 and array2 with some integer elements.
– Step 2b: We calculate the length of the mergedArray which is the sum of the lengths of array1 and array2.
– Step 2c: We create a new integer array, mergedArray, with the calculated length.
– Step 2d: Using two for loops, we fill the mergedArray with the elements of array1 and array2 consecutively.
– Step 2e: Finally, we print the elements of the mergedArray, and the output is 1 2 3 4 5 6.