Search code examples
javabooleanboolean-expression

Is there a post-assignment operator for a boolean?


Hi is something like this possible in Java?

boolean flag = true;
if(flag) return flag = false; // return true and assign false to flag afterwards

To clarify. The above works, but is assigns false first. Want I want to achieve is to return the flag as soon as its true and reset it to false afterwards.

The structure looks something like this:

boolean flag = false;
// some operations which can set the flag true
if(flag){ flag = false ; return true};
// some operations which can set the flag true
if(flag){ flag = false ; return true};
// some operations which can set the flag true
if(flag){ flag = false ; return true};

I was thinking about to do it in one go by return flag = false;


Solution

  • No, there's nothing built-in that does what you describe. You'd do it with a temporary variable:

    boolean flag = true;
    boolean returnValue = flag;
    flag = false;
    return returnValue;
    

    Or based on your further edit to the question ("The structure looks something like this"), you can use !:

    boolean flag = false;
    // some operations which can set the flag true
    if(flag) return !(flag = false);
    // some operations which can set the flag true
    if(flag) return !(flag = false);
    // some operations which can set the flag true
    if(flag) return !(flag = false);
    

    I really, really would not do that. It's unnecessarily obtuse.