How can we initialize a boolean array in Java?


The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays.fill() method in such cases.

Syntax

boolean[] booleanArray;

Example

import java.util.Arrays;

public class BooleanArrayTest {
   public static void main(String[] args) {
      Boolean[] boolArray = new Boolean[5]; // initialize a boolean array
      for(int i = 0; i < boolArray.length; i++) {
         System.out.println(boolArray[i]);
      }
      
      Arrays.fill(boolArray, Boolean.FALSE);
      // all the values will be false
      for(int i = 0; i < boolArray.length; i++) {
         System.out.println(boolArray[i]);
      }
      
      Arrays.fill(boolArray, Boolean.TRUE);
      // all the values will be true
      for (int i = 0; i < boolArray.length; i++) {
         System.out.println(boolArray[i]);
      }
   }
}

Output

null
null
null
null
null
false
false
false
false
false
true
true
true
true
true
raja
Published on 11-Sep-2019 11:43:44
Advertisements