Copy the range of Boolean Array to another array in Java
Declaration :
1 |
public static boolean[] copyOfRange(boolean[] original, int from, int to) |
Explanation :
Purpose | The java.util.Arrays.copyOfRange(boolean[] original int from int to) method copies the specified range of the specified array into a new array.The final index of the range (to) which must be greater than or equal to from may be greater than original.length in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. |
Parameters | original ===> This is the array from which a range is to to be copied. |
from ===> This is the initial index of the range to be copied inclusive. | |
to ===> This is the final index of the range to be copied exclusive. | |
Return Value | This method returns a new array containing the specified range from the original array truncated or padded with false elements to obtain the required length. |
Exception | ArrayIndexOutOfBoundsException — If from < 0 or from > original.length() ,IllegalArgumentException — If if from > to. ,NullPointerException — If original is null. |
Java Program : Example
Below example will explain java.util.Arrays.copyOfRange() 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 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize a Boolean Array boolean[] arr1 = new boolean[] { false, true, true, false }; // Print first array System.out.println("First array:"); for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); } // Copy the array elements to new array with range 0 to 8 boolean[] arr2 = Arrays.copyOfRange(arr1, 0, 8); // 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 11 12 13 14 |
First array: false true true false Printing new array: false true true false false false false false |