How to create a copy of Boolean Array in Java?
Declaration :
1 |
public static boolean[] copyOf(boolean[] original,int newLength) |
Explanation :
Purpose | The java.util.Arrays.copyOf(boolean[] originalint 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. |
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. |
Java Program : Example
Below example will explain java.util.Arrays.copyOf() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Intialize an array arr1 boolean[] arr1 = new boolean[] { false, false }; // Print the array System.out.println("First Array :"); for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); } // Copy array boolean[] arr2 = Arrays.copyOf(arr1, 6); arr2[2] = false; arr2[3] = true; arr2[4] = false; arr2[5] = true; // Print the new array System.out.println("New array:"); for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]); } } } |
Output of Program :
1 2 3 4 5 6 7 8 9 10 |
First Array : false false New array: false false false true false true |