2.5 Compound Boolean Expressions
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.

- || : The expression a || b evaluates to false if both a and b are false.

- ! : The expression !a evaluates to true if a is false and evaluates to false otherwise

(2) Precedence
- The order of
precedence for evaluating logical operators is ! > && > ||.
- Example 1:
- In this example: && has a higher precedence over ||
- Example 2:

- 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: &&

- Example 2: ||

3. Exercises