The logical operators are used for Boolean expressions. A Boolean expression can be in one of two states: True or False. Depending on the state of the expression, different set of code can be executed. Checking the state of a variable is involves condition constructing.
The two basic types of logical operators are: AND, and OR. A condition joined with the AND operator is true only when all of the expression(s) in a statement is true. For example, the following expression
(4 > 2) AND (3 > 1)
is evaluated as true because 4 is greater than 2 and 3 is greater than 1. If either one or more of the conditions joined with an AND operator is false, then the entire expression is false. Consider this expression
(4 > 5) AND (3 > 2)
is evaluated to be false because 4 is not greater than 5. Notice the other condition, 3 greater than 2, is true. As stated earlier, both of the conditions have to be true for a statement to be evaluated as true. Table 1 presents the AND operator truth table, which shows that an expression is true only when both A and B are true; otherwise false.
|Table 1 truth table for AND operator|
|A||B||A AND B|
In comparison, an OR operator is true when at least one of the conditions of an expression is true. The following two statements
(4 < 2) OR (3 > 2)
(15 < 70) OR (13 >= 2)
are true. In the first statement, the second condition is true: 3 is greater than 2. Therefore, the entire expression is evaluated to be true even though the first condition is false: 4 less than 2. In the second statement, both conditions are true; therefore, the entire expression is evaluated to be true.
Table 2 presents the truth table for the OR operator. As the table indicates, the expression is false only when both of the conditions are false. When at least one of the conditions is true, the resulting expression is true.
|Table 2 truth table for OR operator|
|A||B||A OR B|