In Java, Arrays.copyOfRange(original, from, to) returns a new array containing the elements of original from index from up to, but not including, index to. Its length is to - from.
It is Java's way to take a slice or sub-array. Unusually, to may be larger than the array length: the missing positions are padded with 0, false, or null, just like copyOf.
A static method of java.util.Arrays (Java 6+): call it on the class, as in Arrays.copyOfRange(...); there is no Arrays object to create.
Syntax
Pass the array, a start index, and an end index (exclusive).
Overloads exist for all eight primitive types, for T[], and for U[] with a target array type (Class<? extends T[]> newType).
Library declarations
Java
// java.util.Arrays (since Java 6)
public static int[] copyOfRange(int[] original, int from, int to)
public static char[] copyOfRange(char[] original, int from, int to)
public static <T> T[] copyOfRange(T[] original, int from, int to)
public static <T, U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
// also long[], short[], byte[], float[], double[], boolean[]
Parameters
Parameter
Description
original
The source array. Must not be null.
from (int)
First index to copy, inclusive. Must be between 0 and original.length.
to (int)
End index, exclusive. Must be at least from; may be greater than original.length.
Return Value
Return Value
Description
New array
A new array of length to - from holding the copied slice, padded with default values if to goes past the end.
[t1, t2]
[t3, t4]
[t5]
from > to: IllegalArgumentException
from > length: ArrayIndexOutOfBoundsException
How It Works
Step by the chunk size.start takes the values 0, 2, and 4, and each chunk covers two indexes.
A short last chunk.Math.min(start + 2, tasks.length) caps the final end index at 5, so the last chunk holds only t5 instead of being padded with null.
Backwards range.(3, 1) would mean a length of -2, so the method throws IllegalArgumentException.
Start past the end.from = 6 is greater than the length 5, which the documentation answers with ArrayIndexOutOfBoundsException.
Frequently Asked Questions
No. from is inclusive and to is exclusive, so the result has to - from elements.
Yes. The extra positions are filled with 0, false, or null. Only from must stay between 0 and the array length.
IllegalArgumentException when from > to, ArrayIndexOutOfBoundsException when from < 0 or from > length, and NullPointerException when the array is null.
Use Arrays.copyOfRange(array, from, to). It returns a new array; changing it does not change the original.
copyOf always copies from index 0 and takes a length. copyOfRange takes a start and an end index.