Cleanest way to toggle a boolean variable in Java?

前端 未结 9 783
悲哀的现实
悲哀的现实 2020-11-27 10:03

Is there a better way to negate a boolean in Java than a simple if-else?

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}
<         


        
9条回答
  •  有刺的猬
    2020-11-27 10:47

    There are several

    The "obvious" way (for most people)

    theBoolean = !theBoolean;
    

    The "shortest" way (most of the time)

    theBoolean ^= true;
    

    The "most visual" way (most uncertainly)

    theBoolean = theBoolean ? false : true;
    

    Extra: Toggle and use in a method call

    theMethod( theBoolean ^= true );
    

    Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.

提交回复
热议问题