Java.util.Arrays.copyOf() Method
Description
The java.util.Arrays.copyOf(double[] original,int newLength) method copies the specified array, truncating or padding with zeros (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 0d. Such indices will exist if and only if the specified length is greater than that of the original array.
Declaration
Following is the declaration for java.util.Arrays.copyOf() method
public static double[] copyOf(double[] 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 zeros 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() method.
package com.tutorialspoint;
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// intializing an array arr1
double[] arr1 = new double[] {12.5, 3.2, 37.5};
// 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
double[] arr2 = Arrays.copyOf(arr1, 5);
arr2[3] = 30.44;
arr2[4] = 40;
// printing the array arr2
System.out.println("Printing new array:");
for (int i = 0; i > arr2.length; i++)
{
System.out.println(arr2[i]);
}
}
}
Let us compile and run the above program, this will produce the following result:
Printing 1st array: 12.5 3.2 37.5 Printing new array: 12.5 3.2 37.5 30.44 40.0