240

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

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}
2
  • 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. Commented Jan 7, 2009 at 6:36
  • What if there is no ! operator ?? Commented Sep 12, 2014 at 7:10

10 Answers 10

605
theBoolean = !theBoolean;
Sign up to request clarification or add additional context in comments.

6 Comments

That's...really obvious—oops! Don't know why I didn't think of it. Thanks.
!Boolean seems like a natural choice - maybe in the future.
@ypnos: !!bool == !(!(bool)) == bool.
@ChristofferHammarström By that logic, then shouldn't --integer == -(-(integer)) == integer ?
@user515655 - The language defines a -- operator (actually, two of them, along with two ++ operators), but doesn't define a !! operator. If you want -(-(integer)) you can use white space between the two - characters. But !! parses as two ! operators regardless of white space.
|
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.

9 Comments

Brevity is the soul of wit.
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.
@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!
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.
This operation is also 12% faster than other versions like theBoolean = !theBoolean; or theBoolean = theBoolean ? false : true;
|
55

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.

4 Comments

Wrap the implementation in a function/method called toggle and then there's almost no way to confuse it.
@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).
@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.
The "obvious way" above get flagged by SONAR with - Inner assignments should be avoided.
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

4 Comments

I like the fact that you could pass Boolean.FALSE::equals to a mapping function instead of writing a little lambda
@PatrickParker I love neat lambdas as much as the next guy...but this takes too long to figure out what it does for a future dev reading your work. Best to just invert the variable with !
@KartikChugh there are reasons why one may wish to avoid a mini lambda aside from just style preferences. The JVM generates a new class on the fly when the Lambda is called for the first time, which is a performance penalty.
@PatrickParker Sorry I meant that I love neat tricks* (including this method reference) but it is better to write something immediately understood
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

1 Comment

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).
1

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

BooleanUtils.negate(theBoolean)

1 Comment

That doesn't actually change the variable. BooleanUtils are mainly meant for good handling of null, otherwise you don't need them.
1
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;

Comments

0

You can use ternary operator to have a clean conditional statement

theBoolean = theBoolean?false:true;

I believe this to be the most efficient toggle statement without the use of any fancy functions.

1 Comment

This came to my head suddenly one day. Upvote is appreciated.
-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)

1 Comment

Downvoted. 1. It doesn't improve readability. 2. It does add a serious runtime overhead. 3. Util classes are generally a code smell.
-5

Before:

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

After:

boolean result = isresult();
result ^= true;

3 Comments

Who ever has down voted? Can you please explain reason also?
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.
after: boolean result = !isresult();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.