Java Arrays copyOf() Method
Example
Copy an array into a shorter array and into a longer array:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] myNum = {10, 20, 30, 40};
int[] shortNum = Arrays.copyOf(myNum, 2);
int[] longNum = Arrays.copyOf(myNum, 6);
System.out.println(Arrays.toString(shortNum));
System.out.println(Arrays.toString(longNum));
}
}
Definition and Usage
The copyOf() method creates a new array with the given length, and copies the items of an array into it. The original array does not change.
If the new array is shorter, the last items are left out. If it is longer, the extra places get the default value of the type, for example 0 for int, false for boolean and null for String.
Tip: Arrays.toString() returns the items of an array as text, so you can print them.
Syntax
public static type[] copyOf(type[] original, int newLength)
type can be boolean, byte, char, short, int, long, float, double, or an object type such as String.
Parameter Values
| Parameter | Description |
|---|---|
| original | Required. The array to copy. |
| newLength | Required. The length of the new array. |
Technical Details
| Returns: | A new array with the given length. |
|---|---|
| Throws: | NegativeArraySizeException - if newLength is negative. |
Related Pages
❮ Arrays Methods