Java has three logical operators:
!, which respectively stand for and, or, and not. The results of these operators are similar to their meanings in English.
x > 0 && x < 10 is true when
x is both greater than zero and less than 10. The expression
evenFlag || n \% 3 == 0 is true if either condition is true, that is, if
evenFlag is true or the number
n is divisible by 3. Finally, the
! operator inverts a boolean expression. So
!evenFlag is true if
evenFlag is not true.
Logical operators evaluate the second expression only when necessary. For example,
true || anything is always true, so Java does not need to evaluate the expression
false && anything is always false. Ignoring the second operand, when possible, is called short circuit evaluation, by analogy with an electrical circuit. Short circuit evaluation can save time, especially if
anything takes a long time to evaluate. It can also avoid unnecessary errors, if
anything might fail.
If you ever have to negate an expression that contains logical operators, and you probably will, De Morgan’s laws can help:
!(A && B)is the same as
!A || !B
!(A || B)is the same as
!A && !B
Negating a logical expression is the same as negating each term and changing the operator. The
! operator takes precedence over
||, so you don’t have to put parentheses around the individual terms
De Morgan’s laws also apply to the relational operators. In this case, negating each term means using the “opposite” relational operator.
!(x < 5 && y == 3)is the same as
x >= 5 || y != 3
!(x >= 1 || y != 7)is the same as
x < 1 && y == 7
It may help to read these examples out loud in English. For instance, “If I don’t want the case where x is less than 5 and y is 3, then I need x to be greater than or equal to 5, or I need y to be anything but 3.”