This post will discuss how to split an array into two parts in Java. If the array contains an odd number of items, the extra item should be part of the first array.

1. Naive solution

A naive solution is to create two new arrays and assign elements from the first half of the source array to the first array and elements from the second half of the source array to the second array.

Download  Run Code

Output:

[1, 2, 3]
[4, 5]

2. Using System.arraycopy() method

System.arraycopy() copies an array from a specified position in the specified source array to a specified position in the target array. We can make use of this method to split array, as shown below:

Download  Run Code

Output:

[1, 2, 3]
[4, 5]

3. Using Arrays.copyOfRange() method

In both approaches discussed above, we manually allocate memory for both arrays. Java Collection Framework also provides one method, copyOfRange(), that copies the specified range of the source array into a new array and returns that array.

Download  Run Code

Output:

[1, 2, 3]
[4, 5]

That’s all about splitting an array into two parts in Java.