Compound
Boolean Expressions
Master how to combine multiple conditions with logical operators to build powerful decision-making logic in Java.
What Is a Boolean Expression?
A Boolean expression is any expression that evaluates to exactly one of two values: true or false. In Java, the primitive type boolean stores this result.
Why Compound Expressions?
Real programs rarely depend on a single condition. You almost always need to check multiple things at once:
The Three Logical Operators
&& (AND) Truth Table
|| (OR) Truth Table
The ! (NOT) Operator
The NOT operator is unary: it takes a single Boolean operand and returns its opposite.
&& vs ||: Key Distinctions
| && (AND) | || (OR) | |
|---|---|---|
| Result is true when | Both are true | At least one is true |
| Result is false when | Either is false | Both are false |
| Short-circuits when | Left side is false | Left side is true |
| Real-world analogy | Both keys needed | Any key works |
| Precedence | Higher (evaluated first) | Lower (evaluated second) |
Short-Circuit Evaluation
Java stops evaluating a compound expression as soon as the result is determined. This is called short-circuit evaluation.
How to Build Compound Expressions
Example 1: Range Check
Check if a test score is between 0 and 100 inclusive.
Example 2: Eligibility Logic
A student qualifies for a discount if they are a member or if their purchase is over $50.
Example 3: Combined Logic
A ride requires age \(\ge 12\) and height \(\ge 48\) inches, or the rider has a special pass.
De Morgan's Laws
De Morgan's Laws let you distribute the NOT operator across compound expressions by flipping the operator and negating each part.
Common Mistakes
Summary Reference
| Concept | Syntax | Behavior |
|---|---|---|
| AND | && | true only if both true |
| OR | || | true if at least one true |
| NOT | ! | Flips true/false |
| Precedence | \(! > \texttt{&&} > \texttt{||}\) | Use ( ) to clarify |
| De Morgan's 1 | \(!(\text{A} \ \texttt{&&} \ \text{B})\) | \(!\text{A} \ \texttt{||} \ !\text{B}\) |
| De Morgan's 2 | \(!(\text{A} \ \texttt{||} \ \text{B})\) | \(!\text{A} \ \texttt{&&} \ !\text{B}\) |
| Short-circuit | && / || | Stops early if result known |
Question 1 of 5
What does the following expression evaluate to?
\(\texttt{true} \ \texttt{&&} \ \texttt{false} \ \texttt{||} \ \texttt{true}\)
Question 2 of 5
Which expression correctly checks if \(x\) is between \(1\) and \(10\) inclusive?
Question 3 of 5
Using De Morgan's Law, which is equivalent to \(!(\texttt{a} \ \texttt{&&} \ \texttt{b})\)?
Question 4 of 5
Given \(\texttt{String s = null;}\), what happens when this runs?
\(\texttt{if (s != null && s.length() > 0)}\)
Question 5 of 5
What is the value of result after this code runs?
int x = 7; int y = 3; boolean result = !(x > 5 && y > 5) || (x + y == 10);