Question

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?

Was it helpful?

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;

OTHER TIPS

An even cooler way (that is more concise than myBool = !myBool for variable names longer than 4 characters if you want to set the variable):

myBool ^= true;

And by the way, don't use if (something == true), it's simpler if you just do if (something) (the same with comparing with false, use the negation operator).

For a boolean it's pretty easy, a Boolean is a little bit more challenging.

  • A boolean only has 2 possible states: trueand false.
  • A Boolean on the other hand, has 3: Boolean.TRUE, Boolean.FALSE or null.

Assuming that you are just dealing with a boolean (which is a primitive type) then the easiest thing to do is:

boolean someValue = true; // or false
boolean negative = !someValue;

However, if you want to invert a Boolean (which is an object), you have to watch out for the null value, or you may end up with a NullPointerException.

Boolean someValue = null;
Boolean negativeObj = !someValue.booleanValue(); --> throws NullPointerException.

Assuming that this value is never null, and that your company or organization has no code-rules against auto-(un)boxing. You can actually just write it in one line.

Boolean someValue = Boolean.TRUE; // or Boolean.FALSE
Boolean negativeObj = !someValue;

However if you do want to take care of the null values as well. Then there are several interpretations.

boolean negative = !Boolean.TRUE.equals(someValue); //--> this assumes that the inverse of NULL should be TRUE.

// if you want to convert it back to a Boolean object, then add the following.
Boolean negativeObj = Boolean.valueOf(negative);

On the other hand, if you want null to stay null after inversion, then you may want to consider using the apache commons class BooleanUtils(see javadoc)

Boolean someValue = null; // or Boolean.TRUE or Boolean.FALSE;
Boolean negativeObj = BooleanUtils.negate(someValue);

Some prefer to just write it all out, to avoid having the apache dependency.

Boolean someValue = null; // or Boolean.TRUE or Boolean.FALSE;
Boolean negative = (someValue == null)? null : Boolean.valueOf(!someValue.booleanValue());

The most concise way is to not invert the boolean, and just use !myBool later on in the code when you want to check the opposite condition.

myBool = myBool ? false : true;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top