Java program to merge two arrays one after the other
Program
import java.util.Arrays;
import java.util.Scanner;
public class ConcatenateTwoArraysWithoutarraycopy {
public static void main(String[] args) {
int i;
System.out.println("Enter the required size of the first array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
int[] inputFirstArray = new int[size];
System.out.println("Enter the elements of the array: ");
for (i = 0; i < size; i++) {
inputFirstArray[i] = reader.nextInt();
}
System.out.println("Enter the required size of the second array: ");
size = reader.nextInt();
int[] inputSecondArray = new int[size];
System.out.println("Enter the elements of the array: ");
for (i = 0; i < size; i++) {
inputSecondArray[i] = reader.nextInt();
}
int firstLen = inputFirstArray.length;
int secondLen = inputSecondArray.length;
int[] mergedArray = new int[firstLen + secondLen];
int position = 0;
for (int element : inputFirstArray) {
mergedArray[position] = element;
position++;
}
for (int element : inputSecondArray) {
mergedArray[position] = element;
position++;
}
System.out.println("Arrays after merging: ");
System.out.println(Arrays.toString(mergedArray));
}
}
Output
javac .\ConcatenateTwoArraysWithoutarraycopy.java
java ConcatenateTwoArraysWithoutarraycopy
Enter the required size of the first array:
3
Enter the elements of the array:
10
20
30
Enter the required size of the second array:
2
Enter the elements of the array:
40
50
Arrays after merging:
[10, 20, 30, 40, 50