Skip to main content
ICT
Lesson A8 - Control Structures
 
Main   Previous Next
 

E. Logical Operators page 7 of 17

  1. 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.

  2. 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

  3. 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.

  4. 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

  5. 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.

  6. 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

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.