What's the most concise way to get the inverse of a Java boolean value?
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;
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:true
andfalse
. - A
Boolean
on the other hand, has 3:Boolean.TRUE
,Boolean.FALSE
ornull
.
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());