For a boolean
it's pretty easy, a Boolean
is a little bit more challenging.
- A
boolean
only has 2 possible states:
true
and 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());