Logical Operators

Logical operators are used to compare two conditional statements to see if they are true or false and proceed accordingly. Logical operators can return true or false depending on the values on either side of the operator.

OperatorSymbolFunction
AND&&Returns true if the statements on both sides of the operator are true.
OR||Returns true if a statement on either side of the operator is true.
NOT!Returns true is the statement on the right side of the operator is not true.

AND Operator (&&)

The AND operator returns true if the comparison on its both sides are true. It returns false if one or both comparisons on either side are false.

Examples:

StatementReturn valueReason
(5==5)&&(4==4)trueComparisons on both sides are true. 5 is equal to 5 and 4 is equal to 4.
(5>4)&&(5<=6)trueComparisons on both sides are true. 5 is greater than 4 and 5 is less than 6.
("A"<="A")&&
("B"!="C")
trueComparisons on both sides are true. "A" is equal to "A" and "B" is not equal to "C".
(5==5)&&(4==5)falseComparison on the right is false.
("a"!="a")&&
("b"!="c")
falseComparison on the left is false.
(5>6)&&(5>=7)falseComparison on both sides are false.

OR Operator (||)

The OR operator returns true if one comparison on either side of the operator returns true. To return false the comparisons on both sides of the operator must return false.

Examples:

StatementReturn valueReason
(5==5)||(4>5)trueComparisons on the left is true.
(5>6)||(5!=6)trueComparisons on the right is true.
(5==5)||(5<6)trueComparisons on both sides are true.
(5!=5)||(4==5)falseBoth comparisons are false.

NOT Operator (!)

The NOT operator can be used on a single comparison. It makes an expression, than would normally return true, to return false and one that would normally return false to return true.

Examples:

StatementReturn valueReason
!(5==5)false5 is equal to 5 is true but NOT operator makes the statement false.
!(4>5)true4 is greater than 5 is false but NOT operator makes the statement true.

Leave a Reply