We are given two arrays, our task is to merge two arrays into a single array. Let's see how to do it without using any predefined method in Java.
MergeArrays.java
public class MergeArrays
{
public static void main(String args[])
{
int i, k;
int arr1[] = { 1, 2, 3, 4 };
int arr2[] = { 5, 6, 7, 8 };
int combinedSize=arr1.length+arr2.length;
int mergedArray[] = new int[combinedSize];
//storing first array content in mergedArray...
for (i = 0; i < arr1.length; i++)
mergedArray[i] = arr1[i];
for (i = 0, k = arr1.length; k < combinedSize && i < arr2.length; i++, k++)
mergedArray[k] = arr2[i];
System.out.println("After Merging, the array is:");
for (i = 0; i < combinedSize; i++)
System.out.print(mergedArray[i] + " ");
}
}
Output:
After Merging, the array is:
1 2 3 4 5 6 7 8