Can Boolean Arrays Be Initialized in a For Loop?

arrays, initialization, java

Solution

Boolean[] array = new Boolean[5];
for(Boolean value : array) {
    value = false;
}

The java enhanced for loop uses an iterator to go through the array. The iterator returns a reference to the object, but java passes the reference by value, so you are unable to change what the reference points to, which is what you are trying to do with `value = false`.

EDIT: As it turns out, for a normal array, instead of converting to a `List` and using an iterator, java does the following:

for (int i = 0; i < array.length; i++) 
{
    Boolean value = array[i]; //here's how we get the value that's referred to 
    ...                       //in the enchanced for loop  
}

While we are not using an iterator, the fact that Java passes references by value still explains what's going on here. END of EDIT

If this were an array of objects with certain instance members, you would be able change said members, but not what the object, itself, references.

As others have suggested, to get around this, simple use a regular for loop and manually assign values to indexed slots in the array, ie:

Boolean[] b_values = new Boolean[5];
for(int i = 0; i < b_values.length; i++) 
{
    b_values[i] = Boolean.FALSE; 
}

Problem

Just found this SO question that happened to solve my problem with initializing a Boolean array initializing a boolean array in java. However, while it gave me code that will work, the asker wasn't trying the code that I was running that wasn't working, and I'd actually like to know why it doesn't work. This was the code I was trying: ``` Boolean[] array = new Boolean[5]; for(Boolean value : array) { value = false; } ``` This is the functional code from that other question: ``` Boolean[] array = new Boolean[5]; Arrays.fill(array, Boolean.FALSE); ``` I'm just curious why the for loop approach doesn't work?

Original source

Related problems