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.
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:
(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.)