This post will discuss several methods to get a subarray of a non-primitive array between specified indices in Java.

1. Using Arrays.copyOfRange() method

The standard way to get a subarray of an array is to use the Arrays.copyOfRange(), which returns a subarray containing the specified range from the original array, as shown below:

Download  Run Code

Output:

[B, C, D, E]

2. Using Java 8

We can use the Java Stream, introduced in Java SE 8, to get a subarray from an array. The idea is to get a stream of elements between the specified range and then call the toArray() method to accumulate the stream elements into a new array.

Download  Run Code

Output:

[B, C, D, E]

3. Using System.arraycopy() method

System.arraycopy() method can also be used to get a copy from the specified position in the source array to the specified position of the destination array.

Download  Run Code

Output:

[B, C, D, E]

4. Converting to List

Here, the idea is to convert the array into a list and use the subList() method to get elements between the desired range. Then, we use the toArray(T[]) method to copy the list into a newly allocated array.

Please note that this method doesn’t actually copy the array. Both the resultant list and the sublist are backed by the original array and just references the array.

Download  Run Code

Output:

[B, C, D, E]

5. Custom method

We can also write our own custom method, which simply copies the desired elements from the original array into the new array.

Download  Run Code

Output:

[B, C, D, E]

6. Using Apache Commons Lang

Apache Commons ArrayUtils class provides subarray() method that returns an Object subarray containing the elements between specified indices. See how to convert an object array to an Integer array.

Download Code

Output:

[B, C, D, E]

7. Using Arrays.copyOf() method

Finally, Arrays.copyOf() can also copy the specified array to an array of the specified type. But this approach won’t work if the subarray starts at some intermediate index rather than the first index.

Download  Run Code

Output:

[A, B, C, D, E]

That’s all about getting a subarray of an array between specified indexes in Java.