How can two arrays be merged into one array in Java?
In Java, you can merge two arrays into one using either the System.arraycopy() method or the Arrays.copyOf() method. Below are examples of both methods.
- Use the System.arraycopy() method:
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] mergedArray = new int[array1.length + array2.length];
System.arraycopy(array1, 0, mergedArray, 0, array1.length);
System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);
System.out.println(Arrays.toString(mergedArray));
- Utilize the Arrays.copyOf() method:
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int[] mergedArray = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);
System.out.println(Arrays.toString(mergedArray));
Both methods involve copying the second array to the end of the first array, achieving the merging of the two arrays.