Java.util.Arrays.copyOf() Method

Advertisements


Description

The java.util.Arrays.copyOf(float[] 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 0f.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 float[] copyOf(float[] 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
    float[] arr1 = new float[] {10f, 32f, 25f};

    // 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
    float[] arr2 = Arrays.copyOf(arr1, 5);
    arr2[3] = 30f;
    arr2[4] = 15f;   

    // 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:
10.0
32.0
25.0
Printing new array:
10.0
32.0
25.0
30.0
15.0



Advertisements
Advertisements