Cleanest way to toggle a boolean variable in Java?

前端 未结 9 939
悲哀的现实
悲哀的现实 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:40

    theBoolean ^= true;
    

    Fewer keystrokes if your variable is longer than four letters

    Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.

提交回复
热议问题