Using logical operators

Logical operators are handy when you have to deal with two or more conditions. For example, if you are at a convenience store, you can pay for items if you have cash or a credit card. Or is the logical operator in this case.

You can use the following logical operators:

&& Logical AND—returns true only if all conditions are true
|| Logical OR—returns true if any condition is true
! Logical NOT—returns the opposite Boolean value

To see how these operators are used, enter the following code and run it:

// logical operators
(1 == 1) && (2 == 2) // logical AND operator, true because both
operands are true, so true AND true
returns true
(1 == 1) && (2 != 2) // logical AND operator, false because one
operand is false, so true AND false
returns false
(1 == 1) || (2 == 2) // logical OR operator, true because both
operands are true, so true OR true
returns true
(1 == 1) || (2 != 2) // logical OR operator, true because one operand
is true, so true OR false returns true
(1 != 1) || (2 != 2) // logical OR operator, false because both
operands are false, so false OR false
returns false
!(1 == 1) // logical NOT operator, false because 1==1 is true,
so NOT true returns false

The returned Boolean values are true, false, true, true, false, and false, and will be displayed in the Results area.

So far, you've only worked with numbers. In the next section, you'll see how you can perform operations on strings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.36