How to Create a Subarray in Java

  1. Use the copyOfRange() to Create a Subarray From an Array in Java
  2. Use the arraycopy() to Create a Subarray From an Array in Java
How to Create a Subarray in Java

Arrays can be of any required length. While declaring an array, we allocate the memory to the array. We can also initialize the array during the declaration. At times, we may have to extract only some elements from an array.

In this tutorial, we will create a subarray from another array in Java.

Use the copyOfRange() to Create a Subarray From an Array in Java

Java provides us with a way to copy the elements of the array into another array. We can use the copyOfRange() method, which takes the primary array, a starting index, and an ending index as the parameters and copies that subarray to the destined array.

This function is a part of the java.util package. It was introduced after JDK 1.5.

See the following code.

import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
    int a[] = {3, 5, 8, 4, 6, 7};
    int[] b = Arrays.copyOfRange(a, 2, 4);
    for (int i : b) System.out.print(i + "  ");
  }
}

Output:

8 4

Use the arraycopy() to Create a Subarray From an Array in Java

The arraycopy() function is available in the java.lang.System class. It takes arguments as the source array, starting index, destination array, ending index, and length.

For example,

import java.lang.*;
public class Main {
  public static void main(String[] args) {
    int[] a = new int[] {3, 5, 8, 4, 6, 7};
    int[] b = new int[3];
    System.arraycopy(a, 1, b, 0, 3);
    for (int i : b) System.out.print(i + "  ");
  }
}

Output:

5 8 4

This will copy the elements from the specified start index to the end index into the desired array.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Related Article - Java Array