Search code examples
javaboolean-logicboolean-operations

Reassigning a boolean if not true


I have a method foo() and foobar() that both return a boolean. Each of them must be executed regardless of the result.

boolean changed = true;
while(changed) {
    changed = foo();
    if(!changed) {
        changed = foobar();
    }
    else {
        foobar();
    }
}

I want the loop to keep executing for as long as changed is true, but I feel like the second code block of ifs and elses for foobar() is not very... elegant. Is there a better way to write that part so that the variable changed will only be reassigned if it's not already true?

Thanks!


Solution

  • How about:

    changed = foo() | foobar();
    

    Note the use of the bitwise or operator.