Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Arrays.copyOf — copying an array with a different length

Arrays.copyOf creates a new array of a specified length. For int[], it removes trailing elements or fills extra positions with zeros without changing the original.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

int[] copy = Arrays.copyOf(original, newLength);

Arrays.copyOf(int[] original, int newLength) is a static method of java.util.Arrays. It returns a new int[] of length newLength, preserving the order of copied elements.

A shorter copy omits trailing elements; a longer copy contains extra zeros. Equal length also produces a separate array. Changing an element of the int[] copy does not change the original.

Negative newLength causes NegativeArraySizeException, and null for original causes NullPointerException. A value of 0 is valid: the result is an empty array.

Examples

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] original = {4, 7, 9};
        int[] longer = Arrays.copyOf(original, 5);
        int[] shorter = Arrays.copyOf(original, 2);
        longer[0] = 99;

        System.out.println(Arrays.toString(original));
        System.out.println(Arrays.toString(longer));
        System.out.println(Arrays.toString(shorter));
    }
}

Result

[4, 7, 9]
[99, 7, 9, 0, 0]
[4, 7]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources