Merge Two Arrays
This program merges two arrays into one.
Problem Statement
Write a Java program to merge two integer arrays into a single array.
Source Code
| 1 | public class ArrayMerge { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr1 = {1, 2, 3}; |
| 4 | int[] arr2 = {4, 5, 6}; |
| 5 | int[] merged = new int[arr1.length + arr2.length]; |
| 6 | for(int i=0; i<arr1.length; i++) merged[i] = arr1[i]; |
| 7 | for(int i=0; i<arr2.length; i++) merged[arr1.length+i] = arr2[i]; |
| 8 | System.out.print("Merged array: "); |
| 9 | for(int num : merged) System.out.print(num + " "); |
| 10 | } |
| 11 | } |
Program Output
Merged array: 1 2 3 4 5 6
Explanation
A new array merged is created with a combined length, and the first loop copies arr1's elements while the second copies arr2's elements right after them, together forming a merged array demonstrating concatenation.