236

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

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}
Nhan
  • 3,595
  • 6
  • 30
  • 38
Kevin Griffin
  • 14,084
  • 7
  • 28
  • 23
  • oh nice, I was about to ask the same question, although my question would've been specific to javascript/as3, or ECMAScript in general I suppose... which will easily be covered by this question. – matt lohkamp Jan 07 '09 at 06:36
  • What if there is no ! operator ?? – onmyway133 Sep 12 '14 at 07:10

9 Answers9

594
theBoolean = !theBoolean;
Aaron Maenpaa
  • 119,832
  • 11
  • 95
  • 108
182
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.

pateksan
  • 160
  • 1
  • 12
  • 7
    Brevity is the soul of wit. – Paul Brinkley Oct 22 '08 at 22:47
  • 8
    now I get to offhandedly name-drop (syntax-drop?) XOR to look cool in front of my programmer friends. Your answer ought to be merged with the chosen one, together they are pure perfection. – matt lohkamp Jan 07 '09 at 06:39
  • 6
    @ScottStanchfield Such people should learn it. It's not hard at all, it's no hack, and not knowing it often leads to crappy code as e.g. the one this question. This is a real blow up - five lines using the standard conventions! – maaartinus Jun 21 '14 at 13:44
  • 4
    Think about "should learn it" vs "trying to understand what's going on when you have a day to fix a bug". Yes, XOR is cool here, but the number of people I've mentioned XOR to who say "huh?" is staggering. You should always code for the maintenance programmer, making his job as easy as you can, because no matter how well the code is written, reading someone else's code really sucks. – Scott Stanchfield Jun 25 '14 at 15:57
  • But... this allows you to parametrize the negation :) `theBoolean ^= shouldBeNegated;` – estani Jul 03 '14 at 10:31
  • 5
    [This operation is also 12% faster](http://jsperf.com/boolean-toggling) than other versions like `theBoolean = !theBoolean;` or `theBoolean = theBoolean ? false : true;` – Blaine Kasten Jul 28 '14 at 18:06
  • @BlaineKasten apparently not anymore. Everything is running at equal speed (FF43, Ubuntu 15 64-Bit) EDIT: It's 50% slower for me on Chrome 47, while ternary has a speed of "infinity". – Florian Wendelborn Jan 11 '16 at 07:24
  • If you declare a boolean constant with value `true` in a class `T` and you call it `t`, then you can save one additional keystroke: `myVal ^= T.t;`. Not to speak of a static import... `myVal ^= t;`... Unlimited powah! – Timmos Apr 21 '16 at 09:46
  • @BlaineKasten - On Chrome 55 on OS X, this is the slowest by 53%. Interestingly, the ternary expression is the fastest. – Ted Hopp Jan 27 '17 at 04:15
53

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.

Levite
  • 17,263
  • 8
  • 50
  • 50
  • Wrap the implementation in a function/method called toggle and then there's almost no way to confuse it. – Lambage Sep 08 '17 at 19:50
  • @Reiner: For `C` definately, but in `Java` it is not allowed to mix boolean and integer (also things like `while(1)` are not possible in Java). – Levite Apr 05 '18 at 16:57
  • @Lambage: True, but on the downside you can't toggle a boolean by simply passing it, since it is not possible to pass primitives by reference in Java. You would have to reassign the result of the method to your variable, or otherwise create a wrapper class for the boolean. – Levite Apr 05 '18 at 16:57
  • The "obvious way" above get flagged by SONAR with - Inner assignments should be avoided. – Orby Apr 11 '18 at 14:40
8

This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)

Boolean.valueOf(aBool).equals(false)

or alternatively:

Boolean.FALSE.equals(aBool)

or

Boolean.FALSE::equals
Doctor Parameter
  • 1,202
  • 2
  • 15
  • 21
2

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
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • Good approach, but not totally unambiguous (imho). For someone using/reading just "toggle(..)" might think, calling the method (without assigning it again to the variable) might already toggle the underlying variable. It is obvious to us right now seeing the code, but in real life might be quite hard to debug. A better method name might be "opposite" or possibly "negation", to make this somewhat more obvious; or use the first approach with an object `Boolean` and really toggle it within the method (but still somewhat ambiguous). – Levite Jan 31 '19 at 23:58
1

The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang

BooleanUtils.negate(theBoolean)
Alex
  • 21
  • 1
  • 4
  • That doesn't actually change the variable. BooleanUtils are mainly meant for good handling of null, otherwise you don't need them. – Ariel Feb 14 '23 at 23:20
1
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;
Dan Morton
  • 11
  • 3
-2

If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.

public class Util {


public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }

}

then just create a Util object Util u = new Util(); and have something for the return System.out.println( u.flip(bool) );

If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)

Will D.
  • 5
  • 1
  • Downvoted. 1. It doesn't improve readability. 2. It does add a serious runtime overhead. 3. Util classes are generally a code smell. – rds Mar 13 '21 at 13:12
-4

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;
Florian Wendelborn
  • 1,667
  • 1
  • 19
  • 29
Nikhil Kumar
  • 2,618
  • 3
  • 21
  • 24
  • Who ever has down voted? Can you please explain reason also? – Nikhil Kumar Apr 15 '15 at 11:10
  • 11
    Two main reasons I can think of why someone might have downvoted you: 1) Thread necromancy (_come on! the question was asked 7(!) years ago!_) & your answer doesn't bring anything new to the table; 2) The voter expected something "cleaner" (_read: shorter_) - AaronMaenpaa's answer is a prime example of this. – Priidu Neemre Apr 30 '15 at 15:34
  • 3
    after: boolean result = !isresult(); – Petter Friberg Apr 13 '16 at 21:24