30

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);
3
  • 3
    "Next Question" No. Don't change the question. Ask a new one. Changing the question invalidates all the existing answers. Commented Sep 1, 2012 at 16:58
  • You mean start a new thread outside of this one? Commented Sep 1, 2012 at 16:59
  • Yes, he wants you to ask a new question (i.e. a whole new thread) Commented Aug 2, 2017 at 21:20

2 Answers 2

62

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

Sign up to request clarification or add additional context in comments.

5 Comments

That's what I thought. Thanks
Ok, how do I initialize it to True then?
Simple Arrays.fill(array, Boolean.TRUE);
Ok, my goal is to read an input from the user. If the user enters '1' initialize an elements 1-5 to be true. if '2' is entered initialize element from 5-10 to be true.
Sure, sorry about the confusion. I have posted it above.
4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.