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

Two arrays arr1 and arr2 initialized. - New array merged created with combined length. - First loop copies elements of arr1. - Second loop copies elements of arr2 after arr1. - Together forms merged array. - Demonstrates concatenation of arrays. Conclusion: Shows how arrays can be merged into a single array.

Quick Links to Explore