OPERATORS: &&   ||   !



 
The logical operators are generally used with Boolean values and, when they are, they return a Boolean value. However, both && and || actually return the value of one of their operands, so if the relevent operand is not a Boolean value, the operator may return a non-Boolean value.
 
&&
 
This is the logical AND operator, which returns a Boolean true if both the operands are true. Logically it follows that if the first operand is false, then the whole expression is false, and this is how the operator works; It first evaluates the left hand operand, and if this returns false then, without going any further, it returns false for the whole expression. Otherwise it returns the value of the second operand: true or false for a Boolean value, or the actual value itself if non-Boolean. Assuming 'a' to be 3, 'b' to be 5, and 'c' to be 3, the following examples all return true:
 
if((a == c) && (b == 5))
x = "bread" && (c == 3)

 
...while the following return 'cheese':
 
x = (b > c) && "cheese"
x = "bread" && "cheese"

 
||
 
This is the logical OR operator and it returns a value of true if one or both of the operands is true. It works by first evaluating the left-hand operand and, if this is true, disregarding the right-hand one and returning true for the whole expression. If, however, the left-hand operand is false, then it returns the value of the right-hand operand: true or false if Boolean, or else the value itself. These next examples both return true:
 
if((a == c) || (b == 9))
x = (a > b) || (c == 3)

 
...while this one returns 'cheese':
 
x = (a > b) || "cheese"
 
If, however, the first operand is not a Boolean value, the OR operator returns the value of the first operand whether the second is true or not; in the next example 'bread':
 
x = "bread" || (c == 3)
 
!
 
This is the logical NOT operator which returns false if its single operand can be converted to true, or if it is a non-Boolean value:
 
x = !(a == c)
x = !"cheese"

 
...and true if its operand can be converted to false:
 
x = !(a > b)


Copyright 1999-2001 by Infinite Software Solutions, Inc. All rights reserved.
Trademark Information