Java program to concatenate two arrays using array copy method
Program
import java.util.Arrays;
import java.util.Scanner;
public class ConcatenateTwoArraysUsingarraycopy
{
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];
System.arraycopy(inputFirstArray, 0, mergedArray, 0, firstLen);
System.arraycopy(inputSecondArray, 0, mergedArray, firstLen, secondLen);
System.out.println("Arrays after merging: ");
System.out.println(Arrays.toString(mergedArray));
}
}
Output
javac .\ConcatenateTwoArraysUsingarraycopy.java
java ConcatenateTwoArraysUsingarraycopy
Enter the required size of the first array:
3
Enter the elements of the array:
11
22
33
Enter the required size of the second array:
3
Enter the elements of the array:
44
55
66
Arrays after merging:
[11, 22, 33, 44, 55, 66]