Java.util.Arrays.copyOf(T[], int) Method
Description
The java.util.Arrays.copyOf(T[] original, int newLength) method copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
Declaration
Following is the declaration for java.util.Arrays.copyOf(T) method
public static <T> T[] copyOf(T[] original, int newLength)
Parameters
original -- This is the array to be copied.
newLength -- This is the length of the copy to be returned.
Return Value
This method returns a copy of the original array, truncated or padded with nulls to obtain the specified length.
Exception
NegativeArraySizeException -- If newLength is negative.
NullPointerException -- If original is null.
Example
The following example shows the usage of java.util.Arrays.copyOf(T) method.
package com.tutorialspoint;
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// intializing an array arr1
short[] arr1 = new short[]{15, 10, 45};
// printing the array
System.out.println("Printing 1st array:");
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
// copying array arr1 to arr2 with newlength as 5 as Object
Object arr2 = Arrays.copyOf(arr1, 5);
// cast arr2 as short in order to be printable
short[] arr3 = (short[]) arr2;
// printing the array arr2. Since arr3 is a short[],nulls are now 0
System.out.println("Printing new array:");
for (int i = 0; i < 5; i++) {
System.out.println(arr3[i]);
}
}
}
Let us compile and run the above program, this will produce the following result:
Printing 1st array: 15 10 45 Printing new array: 15 10 45 0 0