tags:

views:

3315

answers:

5

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

if (theBoolean) theBoolean = false; else theBoolean = true;
+10  A: 
theBoolean = ! theBoolean;
Andy Lester
+44  A: 
theBoolean = !theBoolean;
Aaron Maenpaa
That's...really obvious—oops! Don't know why I didn't think of it. Thanks.
Kevin Griffin
I vote for a !!bool operator similiar to ++i and --i ;-))
ypnos
!Boolean seems like a natural choice - maybe in the future.
matt lohkamp
+14  A: 
theBoolean ^= true;

Less keystrokes if your variable is longer then four letters :)

nlaq
and it conforms to DRY :)
Tetha
but it's less obvious to readers who aren't all that up on xor...
Scott Stanchfield
Brevity is the soul of wit.
Paul Brinkley
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
A: 

The downside of theBoolean ^= true; is that it returns an integer (0 or 1)

The question is tagged `Java` and in Java this is not the case, it returns a boolean. JLS 15.26: "...The type of the assignment expression is the type of the variable..."
Carlos Heuberger
A: 
theBoolean = theBoolean ? false : true;

EDIT : Why do you have to? Just test the opposite as below :

if (!theBoolean) {
    // do stuff;
}
fastcodejava