Concatenate Two Arrays in Java
How to Concatenate Two Arrays in Java
Concatenation is the process of appending one array to another array. In Java, arrays are objects, so we can use the concat() method to concatenate two arrays into one.
Steps to Concatenate Two Arrays in Java
- Declare and initialize two arrays, for example:
- int[] firstArray = {1, 2, 3};
- int[] secondArray = {4, 5, 6};
- Declare a third array with the size of firstArray plus secondArray:
- int[] thirdArray = new int[firstArray.length + secondArray.length];
- Use System.arraycopy() to copy firstArray:
- System.arraycopy(firstArray, 0, thirdArray, 0, firstArray.length);
- Use System.arraycopy() to copy secondArray:
- System.arraycopy(secondArray, 0, thirdArray, firstArray.length, secondArray.length);
- Print the thirdArray to view the result of the concatenation:
- for (int x: thirdArray) { System.out.print(x + " "); }
Following these steps will produce the following output: 1 2 3 4 5 6