Java Arrays - copyOfRange() Method
The java.util.Arrays.copyOfRange() method is used to copy the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. The resulting array is of the class newType.
Syntax
public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
Here, U is the class of the objects in the original array and T is the class of the objects in the returned array.
Parameters
original |
Specify the array from which a range is to be copied. |
from |
Specify the initial index of the range to be copied, inclusive. |
to |
Specify the final index of the range to be copied, exclusive. |
newType |
Specify the class of the copy to be returned. |
Return Value
Returns a new array containing the specified range from the original array, truncated or padded with nulls to obtain the required length.
Exception
- Throws ArrayIndexOutOfBoundsException, if from < 0 or from > original.length.
- Throws IllegalArgumentException, if from > to.
- Throws NullPointerException, if original is null.
- Throws ArrayStoreException, if an element copied from original is not of a runtime type that can be stored in an array of class newType.
Example:
In the example below, the java.util.Arrays.copyOfRange() method returns a new array containing the specified range from the original array, truncated or padded with nulls to obtain the required length.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an Integer array Integer Arr1[] = {10, 5, 25}; //copy Arr1 into Arr2 from index 1 to 5 Number[] Arr2 = Arrays.copyOfRange(Arr1, 1, 5, Number[].class); //printing Arr1 System.out.print("Arr1 contains:"); for(Integer i: Arr1) System.out.print(" " + i); //printing Arr2 System.out.print("\nArr2 contains:"); for(Number i: Arr2) System.out.print(" " + i); } }
The output of the above code will be:
Arr1 contains: 10 5 25 Arr2 contains: 5 25 null null
❮ Java.util - Arrays