Fill a Boolean Array using Index in Java
Declaration :
1 |
public static void fill(boolean[] a, int fromIndex, int toIndex, boolean val) |
Explanation :
Purpose | The java.util.Arrays.fill(boolean[] a int fromIndex int toIndex boolean val) method assigns the specified boolean value to each element of the specified range of the specified array of booleans.The range to be filled extends from index fromIndex inclusive to index toIndex exclusive. (If fromIndex==toIndex the range to be filled is empty.) |
Parameters | a ===> This is the array to be filled. |
fromIndex ===> This is the index of the first element (inclusive) to be filled with the specified value. | |
toIndex ===> This is the index of the last element (exclusive) to be filled with the specified value. | |
val ===> This is the value to be stored in all elements of the array. | |
Return Value | This method does not return any value. |
Exception | ArrayIndexOutOfBoundsException — if fromIndex < 0 or toIndex > a.length ,IllegalArgumentException — if fromIndex > toIndex |
Java Program : Example
Below example will explain java.util.Arrays.fill() 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 arr[] = new boolean[] { true, false, false, true, false }; // Print the original array System.out.println("Original Array : "); for (boolean val : arr) { System.out.println("Original Element is " + val); } // Use 'fill' to place 'true' in index 1 to 4 Arrays.fill(arr, 1, 4, true); // Print the new array System.out.println("\nNew Array is : "); for (boolean val : arr) { System.out.println("New Element is " + val); } } } |
Output of Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Original Array : Original Element is true Original Element is false Original Element is false Original Element is true Original Element is false New Array is : New Element is true New Element is true New Element is true New Element is true New Element is false |