- The three logical operators in the AP subset are AND, OR, and NOT. These operators are represented by the following symbols in Java:
AND |
&& |
OR |
|| (two vertical bars) |
NOT |
! |
These logical operators allow us to combine conditions. For example, if a dog is gray and weighs less than 15 pounds it is the perfect lap dog.
- The
&&
(and) operator requires both operands (values) to be true for the result to be true.
(true && true) -> true
(true && false) -> false
(false && true) -> false
(false && false) -> false
- The following are Java examples of using the && (and) operator.
((2 < 3) && (3.5 > 3.0)) -> true
((1 == 0) && (2 != 3)) -> false
The &&
operator performs short-circuit evaluation in Java. If the first operand in &&
statement is false, the operator immediately returns false without evaluating the second half.
- The
||
(or) operator requires only one operand (value) to be true for the result to be true.
(true || true) -> true
(true || false) -> true
(false || true) -> true
(false || false) -> false
- The following is a Java example of using the
||
(or) operator.
((2+3 < 10) || (19 > 21)) -> true
The ||
operator also performs short-circuit evaluation in Java. If the first half of an ||
statement is true, the operator immediately returns true without evaluating the second half.
- The
!
operator is a unary operator that changes a boolean
value to its opposite.
(! false == true) -> true
(! true == false) -> true
(! true == true) -> false
!(2 < 3) -> false