Java – Get subarray between Specified Indexes

Before getting into get subarray between specified indexes, let us first learn about subarray.

What is a subarray?

For example, consider an array = [2,3,4], then the subarrays are [2], [3], [4], [2,3], [3,4], and [2,3,4]. But something like [2,4] would not be considered as subarray.

For an array of size n, we can calculate non-empty subarrays by n*(n+1)/2.


Get subarray between Specified Indexes in Java:

The various methods to get subarray between specified indices are as follows:

1. Arrays.copyOfRange()

It is the standard way to get a subarray of an array that returns a subarray from the specified range of an original array. Following is the example:

Output:


2. System.arraycopy()

This is also one of the methods that are used to copy from the specified position of the source array to the destination array.

Example of System.arraycopy():

Output:


3. Arrays.copyOf()

This is also another way of copying the specified array to a specified type of array. But if the sub-array is not at the first index but is at some intermediate index, this method won’t work.

Example of Arrays.copyOf():

Output:


4. Custom Method

This is a method where we can write our own custom method to copy the specified elements from an array to the new array.

Example to demonstrate the Custom method:

Output:


5. Subarray: without copying

Sometimes it may cause a problem in performance while copying the large part of an array. And in such cases, instead of locating a new array, we can use the instance of the same array.

Example of subarray through callback

Output: