The best way to toggle a boolean variable. 07-16-2018, 05:47 AM
#1
You may have used this:
to toggle your Boolean variable. This is the most common way. However, there exists a much more neat (in my opinion) method:
With the above method, you only have to specify the name of your variable once. Say you had a very long variable name. It would be tedious to have to type out that long name two times:
But, doing so only once:
is much, much nicer looking.
Now, how exactly does "^= true" toggle our Boolean variable?
"myBoolean ^= true" is the equivalent of "myBoolean = myBoolean ^ true"
"^" is the XOR (Exclusive OR) operator in Java. It works like this:
If "myBoolean" is false (zero), then we are putting zero and one through the XOR gate, which, looking at the truth table above, produces a result of one (true), therefore inverting our "myBoolean" variable.
If "myBoolean" is true (1), then we are putting one AND one (the "^= true" part) through the XOR gate, which, judging again from the truth table, produces a result of zero (FALSE!)
That's how "myBoolean ^= true" works to invert your variable, why you should use it, and what it is.
Code:
myBoolean = !myBoolean;
to toggle your Boolean variable. This is the most common way. However, there exists a much more neat (in my opinion) method:
Code:
myBoolean ^= true;
With the above method, you only have to specify the name of your variable once. Say you had a very long variable name. It would be tedious to have to type out that long name two times:
Code:
thisIsAVeryLongVariableNameAsAnExampleOfWhyThisMethodAintTooGreat = !thisIsAVeryLongVariableNameAsAnExampleOfWhyThisMethodAintTooGreat;
But, doing so only once:
Code:
thisIsAVeryLongVariableNameAsAnExampleOfWhyThisMethodAintTooGreat ^= true;
is much, much nicer looking.
Now, how exactly does "^= true" toggle our Boolean variable?
"myBoolean ^= true" is the equivalent of "myBoolean = myBoolean ^ true"
"^" is the XOR (Exclusive OR) operator in Java. It works like this:
Code:
myBoolean = myBoolean ^ 1;
If "myBoolean" is false (zero), then we are putting zero and one through the XOR gate, which, looking at the truth table above, produces a result of one (true), therefore inverting our "myBoolean" variable.
If "myBoolean" is true (1), then we are putting one AND one (the "^= true" part) through the XOR gate, which, judging again from the truth table, produces a result of zero (FALSE!)
That's how "myBoolean ^= true" works to invert your variable, why you should use it, and what it is.