How to Get Subarray in Java?

Last Updated : 23 Jul, 2025

In Java, subarrays are the contiguous portion of an array. Extracting subarrays in Java is common when working with data that needs slicing or partitioning. Java does not have a direct method to create subarrays, we can extract subarrays using simple techniques like built-in methods or manual loops.

Example: The simplest way to get a subarray is by using a manual loop. This approach is straightforward and gives us full control over the array slicing.

Java
// Java Program to get a Subarray in Java 
// Using a Simple Loop
public class SubArray {
  
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};

        // Define the range for the subarray
        int a = 1;       // Start index (inclusive)
        int b = 4;       // End index (exclusive)

        // Create the subarray using a loop
        int[] sub = new int[b - a];
        for (int i = a; i < b; i++) {
            sub[i - a] = arr[i];
        }

        System.out.print("");
        for (int n : sub) {
            System.out.print(n + " ");
        }
    }
}

Output
2 3 4 

Other Methods to Get Sub Array

1. Using Arrays.copyOfRange()

The Arrays.copyOfRange() is the easiest and efficient method to get a subarray. It eliminates the need for a manual loop. It is useful when we want a quick and clean way to extract a subarray without need to think about index management.

Java
// Java Program to Get a Subarray 
// Using Arrays.copyOfRange() method
import java.util.Arrays;

public class SubArray {
  
    public static void main(String[] args) {
      
        int[] arr = {1, 2, 3, 4, 5};

        // Extract subarray using copyOfRange
        // From index 1 to 4 (exclusive)
        int[] sub = Arrays.copyOfRange(arr, 1, 4); 

        System.out.println("" + Arrays.toString(sub));
    }
}

Output
[2, 3, 4]

2. Using Java Streams (Java 8+)

In Java 8, Streams provide a modern, functional approach for extracting subarrays. This method is useful when additional processing is needed.

Java
// Java Program to Get a Subarray
// Using Java Streams 
import java.util.Arrays;
import java.util.stream.IntStream;

public class SubArray {
  
    public static void main(String[] args) {
      
        int[] arr = {1, 2, 3, 4, 5};

        // Extract subarray using streams
        int[] sub = IntStream.range(1, 4)     // From index 1 to 4 (exclusive)
                                  .map(i -> arr[i])
                                  .toArray();

        System.out.println("" + Arrays.toString(sub));
    }
}

Output
[2, 3, 4]

Explanation: The IntStream.range(from, to) generates a stream of indices. The .map(i -> array[i]) maps each index to the corresponding array element. The .toArray() method converts the stream back to an array.

Comment