How can I concatenate two arrays in Java?

 

In Java, you can concatenate two arrays using the System.arraycopy method or by using the Arrays.copyOf method. Here are examples of both approaches:

1. Using System.arraycopy:

java
import java.util.Arrays; public class ArrayConcatenationExample { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int[] concatenatedArray = new int[array1.length + array2.length]; System.arraycopy(array1, 0, concatenatedArray, 0, array1.length); System.arraycopy(array2, 0, concatenatedArray, array1.length, array2.length); System.out.println("Concatenated Array: " + Arrays.toString(concatenatedArray)); } }

In this example, System.arraycopy is used to copy the elements of array1 and array2 into a new concatenatedArray.

2. Using Arrays.copyOf:

java
import java.util.Arrays; public class ArrayConcatenationExample { public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {4, 5, 6}; int[] concatenatedArray = Arrays.copyOf(array1, array1.length + array2.length); System.arraycopy(array2, 0, concatenatedArray, array1.length, array2.length); System.out.println("Concatenated Array: " + Arrays.toString(concatenatedArray)); } }

In this example, we first use Arrays.copyOf to create an array of the required size and copy the elements from array1 into it. Then, we use System.arraycopy to copy the elements from array2 into the concatenated array starting from the index where array1 ends.

Both approaches will give you a concatenated array containing all the elements from the two original arrays.

Comments