VOOZH about

URL: https://www.geeksforgeeks.org/java/java-subarray/

⇱ How to Get Subarray in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.


Output
2 3 4 

Other Methods to Get Sub Array

1. Using Arrays.copyOfRange()

TheArrays.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.


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.


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
Article Tags: