How to Get a slice of a primitive array in Java?

You can get a part of a Java array in between two specified indexes in various ways.

By Copying contents:

One way to do so is to create an empty array and copy the contents of the original array from the start index to the endIndex.

Example

import java.util.Arrays;
public class SlicingAnArray {
   public static int[] sliceArray(int array[], int startIndex, int endIndex ){
      int size = endIndex-startIndex;
      int part[] = new int[size];
      //Copying the contents of the array
      for(int i=0; i<part.length; i++){
         part[i] = array[startIndex+i];
      }
      return part;
   }
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = sliceArray(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
   }
}

Output

[225, 56, 96, 3]

Using the copyOfRange() method 

The copyOfRange() method of the java.util.Arrays class accepts an array, two integers representing start and end indexes and returns a slice of the given array which is in between the specified indexes.

Example

import java.util.Arrays;
public class SlicingAnArray {
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = Arrays.copyOfRange(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
   }
}

Output

[225, 56, 96, 3]

Using Java8 stream

import java.util.Arrays;
import java.util.stream.IntStream;
public class SlicingAnArray {
   public static int[] sliceArray(int array[], int startIndex, int endIndex ){
      int size = endIndex-startIndex;
      int part[] = new int[size];
      IntStream stream = IntStream.range(startIndex, endIndex).map(i->array[i]);
      part = stream.toArray();
      //Copying the contents of the array
      for(int i=0; i<part.length; i++){
         part[i] = array[startIndex+i];
      }
      return part;
   }
   public static void main(String args[]){
      int intArray[] = {12, 14, 58, 225, 56, 96 , 3, 45, 8 };
      intArray = sliceArray(intArray, 3, 7);
      System.out.println(Arrays.toString(intArray));
      }
   }

Output

[225, 56, 96, 3]
Updated on: 2026-03-11T23:26:52+05:30

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements