To test more than one condition, use the logical operators && (also called AND) and || (OR).
Operator | Symbol | Example |
---|---|---|
AND | && | grade >= 70 && grade < 80 |
OR | || | grade > 100 || grade < 1 |
NOT | ! | !grade >= 70 |
The logical AND operator evaluates two expressions. If both expressions are true, the logical AND expression is true. Consider this statement:
if ((x == 5) && (y == 5)) { // do something here }
If x and y both equal 5, the expression is true. If either x or y does not equal 5, the expression is false.
Both sides must be true for the entire expression to be true and for the conditional statement to execute.
The logical OR operator evaluates two expressions and if either one is true, the expression is true:
if ((x == 5) || (y == 5)) { // do something here }
If either x or y equals 5 or both equal 5, the expression is true. If x equals 5, the compiler never checks y at all.
A logical NOT statement reverses a normal expression, returning true if the expression is false and false if the expression is true. Here's a statement that uses one:
if (!(grade < 70)) { // do something here }
This expression is true if grade is 70 or greater and false otherwise.
This NOT expression accomplishes the same thing by looking for grades that are not less than 70.