Compound Boolean
Conditions
Learn to combine multiple boolean expressions using logical operators to write powerful, precise conditions in Java.
What Is a Boolean?
In Java, a boolean is a data type with exactly two possible values: true or false. Every comparison and logical test produces a boolean result.
Why Use Compound Conditions?
Real-world decisions rarely depend on a single test. You might need to check multiple criteria at once: Is the user old enough and do they have a valid ID? Is the temperature below freezing or is it raining?
The Three Logical Operators
Truth Table: \(\&\&\) (AND)
Truth Table: \(||\) (OR)
The \(!\) (NOT) Operator
The NOT operator inverts a single boolean value. It is a unary operator: it acts on one operand, not two.
\(\&\&\) vs \(||\): Key Distinction
| \(\&\&\) (AND) | \(||\) (OR) | |
|---|---|---|
| Meaning | Both must be true | At least one must be true |
| Result is true when | true \(\&\&\) true | Any operand is true |
| Result is false when | Any operand is false | false \(||\) false |
| Short-circuit skips when | Left is false | Left is true |
| Real-world analogy | "Must have ticket AND ID" | "Cash OR credit accepted" |
Operator Precedence
When multiple logical operators appear in one expression, Java evaluates them in a specific order. Just like multiplication before addition in math:
How to Write Compound Conditions
Example 1: Range Check
Problem: Check if a variable score is between 0 and 100, inclusive.
Example 2: Eligibility Check
Problem: A person can vote if they are at least 18 and a registered citizen.
Example 3: Mixed Operators
Problem: A student qualifies for the honor roll if their GPA is at least 3.5 or they have perfect attendance and a GPA of at least 3.0.
Using \(!\) with Compound Conditions
The NOT operator can negate an entire compound expression. De Morgan's Laws describe how negation distributes:
Common Mistakes
Summary Reference
| Operator | Symbol | true When | Precedence |
|---|---|---|---|
| NOT | \(!\) | Operand is false | 1 (highest) |
| AND | \(\&\&\) | Both operands true | 2 |
| OR | \(||\) | At least one true | 3 (lowest) |
Question 1 of 5
What does the following expression evaluate to?
\(\text{true && false || true}\)
Question 2 of 5
Which expression correctly checks if \(x\) is between 1 and 10, inclusive?
Question 3 of 5
What is the value of \(!(\text{true && false})\)?
Question 4 of 5
Given int x = 5;, what does this print?System.out.println(x > 3 || x / 0 > 1);
Question 5 of 5
By De Morgan's Law, which expression is equivalent to \(!(a \text{ && } b)\)?