Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a boolean array to false

Tags:

java

arrays

I have this piece of code below. How do I initialize each element = false?

boolean[] seats = new boolean[10]

I saw a similar question. But, the second line didnt make sense to me (Can you explain the 2nd line?).

 Boolean[] array = new Boolean[size];
 Arrays.fill(array, Boolean.FALSE);
like image 741
AppSensei Avatar asked Sep 01 '12 16:09

AppSensei


People also ask

How do you initialize a boolean array as 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.

How do you initialize a boolean array with false in C++?

in guaranteed to initialize the whole array with null-pointers of type char * . bool myBoolArray[ARRAY_SIZE] = { false }; char* myPtrArray[ARRAY_SIZE] = { nullptr }; but the point is that = { 0 } variant gives you exactly the same result. T myArray[ARRAY_SIZE] = {};

How do you set a boolean to a false?

boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false. Notice that the assignment operator is a single equals sign ( = ).


2 Answers

The default value for the elements in a boolean[] is false. You don't need to do anything.

The reason it's necessary for Boolean[] is because the default value is null.


To initialize to true, use the overload of Arrays.fill that accepts a boolean[].

boolean[] seats = new boolean[10];
Arrays.fill(seats, true);

See it working online: ideone

like image 168
Mark Byers Avatar answered Sep 23 '22 08:09

Mark Byers


A boolean is initialized to false by default. So you need not to do anything specific here. When you create an array of booleans and don't initialize it all the elements will be be false.

how do I initialize it to True then?

Simple Arrays.fill(array, Boolean.TRUE);

like image 29
Bharat Sinha Avatar answered Sep 21 '22 08:09

Bharat Sinha