2.5 Compound Boolean Expressions

0 阅读1分钟

1. Exam Points

  • Use logic operators &&, || , !
  • Precedence: ! > && > ||, left to right
  • Short-circuit evaluation: a && b, a || b
  • Note:
  • For a method with a return type, a value must be returned (in all the cases).
  • Left to right: in a>b && c>d, a>b is evaluated first

2. Knowledge Points

(1) Compound Boolean Expressions

  • Commonly used operators in a boolean expression:
    • Relational operators: <, >, <=, >=, ==, !=
    • Logical operators: && (and), || (or), ! (not)
      • && : The expression a && b evaluates to true if both a and b are true and evaluates to false otherwise.
        image.png
      • || : The expression a || b evaluates to false if both a and b are false. image.png
      • ! : The expression !a evaluates to true if a is false and evaluates to false otherwise
        image.png

(2) Precedence

  • The order of precedence for evaluating logical operators is ! > && > ||.
    • Example 1:
      image.png
      • In this example: && has a higher precedence over ||
    • Example 2:
      image.png
      • In this example: first !, then &&, and then ||

(3) Short-circuit evaluation (短路评估/求值)

  • Short-circuit evaluation (短路评估/求值) occurs when the result of a logical operation using && or || can be determined by evaluating only the first Boolean expression.
    • Example 1: &&
      image.png
    • Example 2: ||
      image.png

3. Exercises