Java.util.Arrays.copyOf() Method

Advertisements


Description

The java.util.Arrays.copyOf(boolean[] original,int newLength) method copies the specified array, truncating or padding with false (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 false. 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 boolean[] copyOf(boolean[] 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 false elements 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
    boolean[] arr1 = new boolean[] {true, false};

    // 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 4
    boolean[] arr2 = Arrays.copyOf(arr1, 4);
    arr2[2] = false;
    arr2[3] = true;

    // 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:
true
false
Printing new array:
true
false
false
true



Advertisements
Advertisements