There are a number of boolean expression patterns that can easily be rewritten to make them simpler. Boolean expressions involving comparisons with boolean literals, ternary conditionals with a boolean literal as one of the results, double negations, or negated comparisons can all be changed to equivalent and simpler expressions.

If A and B are expressions of boolean type, you can simplify them using the rewrites shown below. These rewrites are equally suitable for the primitive type boolean and the boxed type Boolean.

ExpressionSimplified expression
A == trueA(*)
A != falseA(*)
A == false!A
A != true!A
A ? true : BA || B
A ? B : falseA && B
A ? B : true!A || B
A ? false : B!A && B
A ? true : falseA(*)
A ? false : true!A
!!AA(*)

Note that all of these rewrites yield completely equivalent code, except possibly for those marked with (*) when A has type Boolean. These can depend on the context if null values are involved. This is because a comparison or test of a Boolean will perform an automatic unboxing conversion that throws a NullPointerException if null is encountered, so the rewrites marked (*) are only completely equivalent if the surrounding context of the expression unboxes the value, for example by occurring as the condition in an if statement.

In addition to the rewrites above, negated comparisons can also be simplified in the following way:

ExpressionSimplified expression
!(A == B)A != B
!(A != B)A == B
!(A < B)A >= B
!(A > B)A <= B
!(A <= B)A > B
!(A >= B)A < B

In the following example the method f2 is a straightforward simplification of f1; they will both throw a NullPointerException if a null is encountered. A similar rewrite of g1 would however result in a method with a different meaning, and a rewrite along the lines of g2 might be more appropriate. In any case, care should be taken to ensure correct behavior for null values when the boxed type Boolean is used.

  • The Java Language Specification: Logical Complement Operator !, Boolean Equality Operators == and !=, Conditional-And Operator &&, Conditional-Or Operator ||, Conditional Operator ? :.