Compound Boolean Expressions
Compound Boolean Expressions
Overview
- A Compound Boolean Expression is an expression that combines multiple Boolean expressions using logical operators.
- It is used in decision-making statements to evaluate multiple conditions at once.
- The result of a compound Boolean expression is either
true
orfalse
.
Logical Operators
- Logical AND (
&&
) operator: Returnstrue
only if both the Boolean expressions are true. - Logical OR (
||
) operator: Returnstrue
if any one of the Boolean expressions is true. - Logical NOT (
!
) operator: Returns the inversion of a single Boolean expression. If the expression istrue
,!
will make itfalse
, and vice versa.
Short Circuiting
- Short-circuit evaluation is a feature in Java where the second operand in AND (
&&
) and OR (||
) expressions is evaluated only if necessary. - In an AND expression, if the first operand is
false
, the whole expression will befalse
regardless of the second operand, so the second operand is not evaluated. This is because both operands need to betrue
for an AND expression to be true. - For OR expressions, if the first operand is
true
, the whole expression will betrue
regardless of the second operand, so the second operand is not evaluated. This is because only one operand needs to betrue
for an OR expression to be true.
Order of Operations
- Order of operations, also known as operator precedence, for Boolean operators is NOT, AND, and then OR.
- Boolean expressions inside brackets (
()
) are evaluated first. - If multiple operators with the same precedence appear in a row, the expression is evaluated from left to right.
The if-else Statement
- The if-else statement executes a block of code if a specified Boolean expression is
true
; otherwise, it executes another block of code. - Compound Boolean expressions can be used in the if-else statement to decide which block of code to execute based on multiple conditions.
The switch Statement
- The switch statement allows variable to be tested for equality against a list of values.
- It is important to note that compound Boolean expressions cannot be used in a switch statement.
Caution
- Mixing AND and OR operators in a compound Boolean expression without proper bracketing (
()
) can lead to unexpected results due to operator precedence.