Collections

Arrays copyOf in Java Code With Examples

Table of Contents

Program

import java.util.Arrays;
public class ArrayCopyOf 
{
    public static void main(String[] args)
    {
		int[] arr = new int[] { 99, 88, 77 };
		System.out.println("Default Array:");
	   for (int i = 0; i < arr.length; i++)
	   {
		System.out.println(arr[i]);
	   }
		int[] copy = Arrays.copyOf(arr, 5);
		copy[3] = 66;
		copy[4] = 55;
		System.out.println("After using Copy:");
	   for (int i = 0; i < copy.length; i++) 
	   {
		System.out.println(copy[i]);
	   }
    } 
}

Output

Default Array:
99
88
77
After using Copy:
99
88
77
66
55

Description

public static int[] copyOf​(int[] original, int newLength)

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 0. Such indices will exist if and only if the specified length is greater than that of the original array.

Parameters:

original – the array to be copied
newLength – the length of the copy to be returned

Returns:

a copy of the original array, truncated or padded with zeros to obtain the specified length

Throws:

NegativeArraySizeException – if newLength is negative
NullPointerException – if original is null

Since:

1.6