Logical Operators
In propositional logic, a statement can be true or false (like a Boolean variable in Java).
For two statements \(p\) and \(q\), the statement “p and q” is true if and only if both \(p\) and \(q\) are true. The statement “p and q” is written \[ p \land q \]
The statement “p or q” is true if and only if either \(p\) or \(q\) is true, and is written \[ p \lor q \]
The statment “not p” is true if and only if \(p\) is false, and is written \[ \neg p \]
We can illustrate the logical operators with truth tables, where 0 means false and 1 means true.
\[ \begin{array}{|c|cc|} \hline \land & 0 & 1 \\ \hline 0 & 0 & 0 \\ 1 & 0 & 1 \\ \hline \end{array} \]
\[ \begin{array}{|c|cc|} \hline \lor & 0 & 1 \\ \hline 0 & 0 & 1 \\ 1 & 1 & 1 \\ \hline \end{array} \]
Java has special symbols for the logical operators:
\[ \begin{array}{|c|c|c|} \hline \text{operator} & \text{logic symbol} & \text{Java symbol} \\ \hline \text{and} & \land & \text{\&\&} \\ \text{or} & \lor & \text{||} \\ \text{not} & \neg & \text{!} \\ \hline \end{array} \]
You might notice that the “and” table looks like a multiplication
table, and the “or” table looks like addition. In Java, the
&&
operator has higher precedence than the
||
operator, which is consistent with multiplication
having higher precedence than addition.
You might also notice that the symbol \(\land\) for “and” looks like the intersection symbol from set theory \(\cap\), and the “or” symbol \(\lor\) looks like the union symbol \(\cup\). Recall that the intersection \(A \cap B\) is the set of things that are in both \(A\) and \(B\), while the union \(A \cup B\) is the set of things that are in either \(A\) or \(B\).
The logical operators have something like a “distributive property”. These are called De Morgan’s laws:
\[ \begin{aligned} \neg (p \land q) &\iff (\neg p) \lor (\neg q) \\ \neg (p \lor q) &\iff (\neg p) \land (\neg q) \\ \end{aligned} \]
Here’s an example to convince yourself that De Morgan’s laws are true. Let \(p\) be the statement “I received an A in Math”, and \(q\) be the statement “I received an A in Science”. Then if is not true that you received an A in both Math and Science, then either you didn’t receive an A in Math, or you didn’t receive an A in Science. Challenge: Use a Venn diagram to convince yourself that De Morgan’s laws are true.