This post will discuss how to get a slice of a primitive array in Java. In other words, get a subarray of a given primitive array between specified indexes.

1. Using Arrays.copyOfRange() method

The idea is to use the Arrays.copyOfRange() to copy the specified range of the specified array into a new array. Arrays class provides several overloaded versions of the copyOfRange() method for all primitive types.

Download  Run Code

Output:

[2, 3, 4, 5]

2. Using Java 8

From Java 8 onwards, we can simply get a stream of elements between the specified range and then call the toArray() method to accumulate the stream elements into a corresponding primitive array.

Download  Run Code

Output:

[2, 3, 4, 5]

3. Using Apache Commons Lang

Apache Commons provides the ArrayUtils class that has several utility methods for primitive arrays. It has a subarray() method that can produce a primitive subarray containing the elements between specified indexes.

Download Code

Output:

[2, 3, 4, 5]

4. Naive solution

Finally, we can write our own custom method, which creates a new array and copy the elements from the original array to the new array by iterating over the array between specified indexes.

Download  Run Code

Output:

[2, 3, 4, 5]

That’s all about getting a slice of a primitive array in Java.