Get Subarray between Specified Indexes in Java

Before getting into the programming on subarray between specified indexes, let us first learn about the 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 a subarray of an array between specified indexes in Java

The various methods to get java array subarray between specified indices is 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:

int[] copyOfRange(int[] original, int from index number, int to index number)

import java.util.Arrays;

public class Main 
  {
    public static void main (String[] args) 
    {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] arrayResult = Arrays.copyOfRange(arr, 3, 9);
        System.out.println(Arrays.toString(arrayResult));
    }
  }

Output:

[4, 5, 6, 7, 8, 9]


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.

public static vois arraycopy(Object source, srcPpos, Object destination, destPos, int length)

Example of System.arraycopy():

import java.util.Arrays;

public class Main 
 {
    public static void main (String[] args) 
    {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] arrayResult = new int[3];
        System.arraycopy(arr, 3, arrayResult, 0, 3);
        System.out.println(Arrays.toString(arrayResult));
    }
}

Output:

[4, 5, 6]

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():

import java.util.Arrays;

class Main
{
   public static void main(String[] args)
   {
      String[] array = new String [] {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
		
      System.out.println("The sub_array:");
       //Here startingPosition is 0
      String[] sub_array = Arrays.copyOf(array, 6, String[].class);
      System.out.println(Arrays.toString(sub_array));
   }
}

Output:

The sub_array:
[A, B, C, D, E, F]


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:

import java.util.Arrays;

class Main
{
 public static void main(String[] args)
 {
  String[] array = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
  int startPos = 3, endPos = 6;
  int finalPos = (endPos - startPos) + 1;

   System.out.println("The sub_array:");
   String[] sub_array = new String[finalPos];
   for (int i = 0; i < sub_array.length; i++) 
   {
    sub_array[i] = array[startPos + i];
   }

  System.out.println(Arrays.toString(sub_array));
 }
}

Output:

The sub_array:
[D, E, F, G]


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

import java.util.function.Consumer;

public class Main 
{
 public static void main (String[] args) 
 {
  int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  System.out.println("The result:");
  arrayResult(array, 3, 9, System.out::println);
 }

 public static void arrayResult (int[] ts, int from, int to,Consumer<Object> rangeConsumer) 
 {
  for (int i = from; i < to; i++) 
        rangeConsumer.accept(ts[i]);
      
 }
}

Output:

The result:
4
5
6
7
8
9