This post will discuss how to join two primitives arrays in Java. The solution should contain all elements of the first array, followed by all elements the second array.

1. Using Java 8

We know that Java 8 has IntStream to deal with primitive ints. The idea is to get IntStream of elements present in both arrays and concatenate them using IntStream.concat() method. Finally, convert IntStream back to primitive int[] using toArray().

We can also use IntStream.of() method in place of Arrays.stream() for getting the IntStream from primitive int array.

 
For a primitive array of double and long type, we can use DoubleStream and LongStream, respectively. For example,

2. Using System.arraycopy() method

System.arraycopy() provides a convenient and very efficient way to copy arrays in Java. We can make use of this method to copy elements of the given arrays into a newly allocated empty array.

 
We can also use Arrays.copyOf() along with System.arraycopy(), as shown below:

3. Using Guava Library

Guava provides several utility classes pertaining to primitives, like Ints for int, Floats for float, Doubles for double, Longs for long, Booleans for boolean, and so on. Each utility class has a concat() method that can combine specified primitive arrays into a single array.

4. Using Apache Commons Lang

Apache Commons Lang also provides static utility methods pertaining to int primitives that are not already found in either Integer or Arrays. One such method is ArrayUtils.addAll(), which can join two arrays. This method is overloaded for all primitives types and object arrays.

 
Please note that all the above-mentioned methods will throw a NullPointerException if any specified array is null. We can easily add the following snippet at the starting of each method to handle nulls.

That’s all about joining two arrays in Java.