1

I have a boolean array

boolean[] test = {
    false,
    true,
    true,
    false,
    true
};

and I'm trying to flip (true to false, and false to true) the values with "for-each" statement like so:

for(boolean x : test) {
    x = !x;
}

But it's only changing the x variable in the local scope.

I'm new to Java and I want to ask how this could be done and if this is the right approach. I've searched a lot, but most of the examples are used to collect data from the array without modifying it.

1
  • Have you tried to put your variable in list ? and actually what do you actually want ?? Commented Jan 23, 2012 at 13:39

6 Answers 6

9

No, that's not the right approach. The enhanced for loop doesn't let you change the values of what you're iterating over. To invert the array, you'd want to use a regular for loop:

for (int i = 0; i < test.length; i++) {
    test[i] = !test[i];
}

(Note that the enhanced for loop would let you make changes to the objects which any array elements referred to, if they were classes - but that's not the same thing as changing the value of the element itself.)

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

1 Comment

We are not allowed to change the value we are iterating over, but why is so? What could be the consequences if we were allowed to do so
2

You will need to use a non-enhanced for loop if you want affect the values of test:

for (int i = 0; i < test.length; ++i) {
  test[i] = !test[i];
}

2 Comments

Wouldn't the element test[0] remain unchanged because of the pre-increment ++i ?
No. The increment expression is evaluated AFTER each execution of the loop. So, the first execution of the loop i would be assigned the value 0.
1

You cannot change the item in a for-each loop. Can you use a regular loop instead?

for (int i=0; i < test.length; i++)
{
    test[i] = !test[i];
}

Comments

1

You don't do that with a for each, as the for each reads the value of the array, and stores it in a local variable, as you said. You need to iterate the array and access the index directly. I won't post any code so you can find and think about it.

Comments

1

No surprises that it does not work. You are manipulating a local variable after all and its not an object and not a reference. Use a normal for loop and modify corresponding position.

Comments

0

The enhanced for loop is creating a new variable x and setting the value locally each time because boolean is a primitive and is therefore not passed by reference. For this, you will need to use the old for loop.

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.