Java – Slice an Array

To slice an array from specific starting index to specific ending index, call Arrays.copyOfRange() method and pass the array, starting index, and ending index as arguments.

Examples

In the following example, we take an integer array of length 10 and slice it from index=3 to index=8.

Main.java

</>
Copy
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
        int start = 3;
        int end = 8;

        int newArr[] = Arrays.copyOfRange(arr, start, end);

        System.out.println("Original : " + Arrays.toString(arr));
        System.out.println("Sliced   : " + Arrays.toString(newArr));
    }
}

Output

Original : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Sliced   : [8, 10, 12, 14, 16]

Conclusion

In this Java Tutorial, we learned how to slice an Array in Java using Arrays.copyOfRange() method with examples.