Java Concatenate Arrays
There are many ways in which you can concatenate two or more arrays in Java.
To concatenate arrays, you can use a looping statement, iterate over elements of the arrays and create a new array containing all the elements of input arrays. Or you can use ArrayUtils of apache commons library and concatenate arrays. Or you can also use Arrays class and its methods like copyOf(), to concatenate arrays.
In this tutorial, we will go through each of the above said process and write Java programs to demonstrate how we can concatenate arrays.
Example 1 – Concatenate Arrays – For Loop and Array Traversing
In the following program, we take two arrays, traverse them using Java For Loop, and create a new array with all the elements from these two input arrays. The resulting array will have a length equal to the sum of lengths of the two input arrays.
Java Program
/**
* Java Example Program, to Concatenate Arrays
*/
public class ConcatenateArrays {
public static void main(String[] args) {
//two arrays
int[] arr1 = {1, 4, 9};
int[] arr2 = {16, 25, 36};
//concatenate arrays
int[] result = new int[arr1.length+arr2.length];
for(int i=0;i<arr1.length;i++) {
result[i] = arr1[i];
}
for(int i=0;i<arr2.length;i++) {
result[arr1.length+i] = arr2[i];
}
//print the result
for(int element: result) System.out.println(element);
}
}
Output
1
4
9
16
25
36
Example 2 – Concatenate Arrays – ArrayUtils.addAll()
In the following program, we will use ArrayUtils.addAll() method, to concatenate two arrays.
Java Program
import org.apache.commons.lang.ArrayUtils;
/**
* Java Example Program, to Concatenate Arrays
*/
public class ConcatenateArrays {
public static void main(String[] args) {
//two arrays
int[] arr1 = {1, 4, 9};
int[] arr2 = {16, 25, 36};
//concatenate arrays
int[] result = ArrayUtils.addAll(arr1, arr2);
//print the result
for(int element: result) System.out.println(element);
}
}
Output
1
4
9
16
25
36
Example 3 – Concatenate Arrays – Arrays.copyOf() and System.arraycopy()
In the following program, we will use Arrays.copyOf() method, and System.arraycopy() method to concatenate two arrays.
Java Program
import java.util.Arrays;
/**
* Java Example Program, to Concatenate Arrays
*/
public class ConcatenateArrays {
public static void main(String[] args) {
//two arrays
int[] arr1 = {1, 4, 9};
int[] arr2 = {16, 25, 36};
int[] result = Arrays.copyOf(arr1, arr1.length + arr2.length);
System.arraycopy(arr2, 0, result, arr1.length, arr2.length);
//print the result
for(int element: result) System.out.println(element);
}
}
Output
1
4
9
16
25
36
Conclusion
In this Java Tutorial, we learned how to concatenate arrays in Java, with the help of example programs.