Java Collection Tutorial - Java Arrays.copyOfRange(T[] original, int from, int to)








Syntax

Arrays.copyOfRange(T[] original, int from, int to) has the following syntax.

public static <T> T[] copyOfRange(T[] original,   int from,   int to)

Example

In the following code shows how to use Arrays.copyOfRange(T[] original, int from, int to) method.

/* w w w .  j a v a 2 s.  c om*/

import java.util.Arrays;

public class Main {

   public static void main(String[] args) {

      short[] arr1 = new short[]{15, 10, 45};

      System.out.println(Arrays.toString(arr1));

      // copying array arr1 to arr2 with range of index from 1 to 3
      Object arr2 = Arrays.copyOfRange(arr1, 1, 3);

      // cast arr2 as short in order to be printable
      short[] arr3 = (short[]) arr2;

      System.out.println(Arrays.toString(arr3));
   }
}

The code above generates the following result.