What's the most concise way to get the inverse of a Java boolean value?

faq picture faq · Oct 11, 2010 · Viewed 53.5k times · Source

If you have a boolean variable:

boolean myBool = true;

I could get the inverse of this with an if/else clause:

if (myBool == true)
 myBool = false;
else
 myBool = true;

Is there a more concise way to do this?

Answer

BoltClock picture BoltClock · Oct 11, 2010

Just assign using the logical NOT operator ! like you tend to do in your condition statements (if, for, while...). You're working with a boolean value already, so it'll flip true to false (and vice versa):

myBool = !myBool;