1. Introduction
Merging arrays is a common operation where we combine the elements of two arrays into a third one. This is particularly useful in sorting algorithms, data manipulation, and whenever we need to consolidate data. In this blog post, we will learn how to merge two arrays into a third array in Java.
2. Program Steps
1. Initialize two arrays array1 and array2.
2. Create a third array mergedArray with a length equal to the sum of the lengths of array1 and array2.
3. Copy elements of array1 and array2 into mergedArray.
4. Display the mergedArray.
3. Code Program
public class MergeArrays {
public static void main(String[] args) {
// Step 1: Initialize two arrays array1 and array2
int[] array1 = {1, 3, 5, 7};
int[] array2 = {2, 4, 6, 8};
// Step 2: Create a third array mergedArray with a length equal to the sum of the lengths of array1 and array2
int[] mergedArray = new int[array1.length + array2.length];
int i = 0;
// Step 3: Copy elements of array1 and array2 into mergedArray
for (int elem : array1) {
mergedArray[i++] = elem;
}
for (int elem : array2) {
mergedArray[i++] = elem;
}
// Step 4: Display the mergedArray
System.out.print("Merged Array: ");
for (int elem : mergedArray) {
System.out.print(elem + " ");
}
}
}
Output:
Merged Array: 1 3 5 7 2 4 6 8
4. Step By Step Explanation
In Step 1, we initialize two integer arrays array1 and array2 with some elements.
For Step 2, a third array mergedArray is created, and its length is set as the sum of the lengths of array1 and array2.
During Step 3, we copy each element from array1 and array2 into mergedArray using two separate for-each loops.
Finally, in Step 4, we print out the mergedArray, which now contains all elements from array1 and array2.