Search code examples
javabooleaninverse

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


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?


Solution

  • 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;