arrays copyof in java

By | August 23, 2020

Arrays copyof in Java:

Syntax:

copyOf
public static <T> T[] copyOf(T[] original, int newLength)

Method explanation:

Arrays copyOf in java:

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.

In short, it creates a new array with same or different length using the first array contents.

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 nulls to obtain the specified length

Throws:

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

This method is available in java since 1.6 version.

Example 1:

Output:

Example 2:

Output:

What is the output if copiedArray’s (or 2nd array) length is greater than first array:

Zeros will be printed if second array’s length is greater than first array.

arrays copyof in java

Arrays copyof in java example.

 

 

 

 

 

 

 

 

 

Recommended Posts:

StringUtils lowercase

StringUtils startsWith

StringUtils equalsAny

arrays copyof in java 1

Leave a Reply

Your email address will not be published. Required fields are marked *