Is there a better way to negate a boolean in Java than a simple if-else?
if (theBoolean) { theBoolean = false; } else { theBoolean = true; } Is there a better way to negate a boolean in Java than a simple if-else?
if (theBoolean) { theBoolean = false; } else { theBoolean = true; } theBoolean = !theBoolean; theBoolean ^= true; Fewer keystrokes if your variable is longer than four letters
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; 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.
If you use Boolean NULL values and consider them false, try this:
static public boolean toggle(Boolean aBoolean) { if (aBoolean == null) return true; else return !aBoolean; } If you are not handing Boolean NULL values, try this:
static public boolean toggle(boolean aBoolean) { return !aBoolean; } These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.
Usage
boolean bTrue = true boolean bFalse = false boolean bNull = null toggle(bTrue) // == false toggle(bFalse) // == true toggle(bNull) // == true Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:
Boolean b = false b = b.toggle() // == true Before:
boolean result = isresult(); if (result) { result = false; } else { result = true; } After:
boolean result = isresult(); result ^= true;