Logical operators
|| (OR) and
&& (AND) are
left-associative, meaning their parameters are evaluated from left to right. If the first value resolves to
true in an OR operation (
||) or
false in an AND operation (
&&), the overall result is determined immediately to be the same. In such cases, what is known as
short-circuiting occurs. This means that the second argument is not evaluated because it is unnecessary.
This feature can be conveniently exploited, for example, to check for null in a single line:
return param != null && param.getBoolMember();
However, this can sometimes lead to unexpected bugs, especially if the second argument is a function with side effects rather than a simple variable. For situations where short-circuiting is undesirable, the
non-short-circuiting versions of these operators are used:
| and
&. These are
logical variants of "bitwise OR" and "bitwise AND".
Additionally, the "exclusive or" operator
^ is available. It is rarely used for boolean parameters though, because it is functionally equivalent to the more intuitive
!=. Other bitwise operators are not applicable for logical arguments.