Back
How to initialize an array of boolean datatype and assign false value to all the indices of the array?
You can do it in two ways:
Boolean[] arr=new boolean[size];
This would set all the values to false by default
Arrays.fill(arr,Boolean.false);
This would set all the values to false explicitly.
To Initialize a boolean array in Java with all elements set to true (or any specific value). Iterate through each element using a loop. Here is how it works:
public class BooleanArrayInitialization {
public static void main(String[] args) {
boolean[] boolArray = new boolean[5]; // Creates an array of 5 booleans (default: false)
for (int i = 0; i < boolArray.length; i++) {\
boolArray[i] = true; // Sets each element to true\
}
/// Print the array to check
for (boolean value : boolArray) {
System.out.println(value); // Outputs: true true true true true
In this case, the for loop runs on the array and assigns all the elements to true.
31k questions
32.8k answers
501 comments
693 users