AP Computer Science A · Unit 2: Selection & Iteration
2.5 Compound Boolean Expressions
Combining conditions with && and ||
Compound boolean expressions combine simple conditions using logical operators: && (AND, true only if both sides are true), || (OR, true if at least one side is true), and ! (NOT, reverses a boolean value). These let you test multiple conditions in one expression, like `(age >= 13 && age <= 19)` to check for teenagers.
Short-circuit evaluation
Java uses short-circuit evaluation: for `&&`, if the left operand is false, the right is never evaluated (result is already false). For `||`, if the left operand is true, the right is skipped. This can prevent errors, like avoiding a division by zero or a null reference check: `(x != 0 && 10/x > 1)`.
De Morgan's Laws
De Morgan's Laws let you rewrite negated compound expressions: `!(a && b)` is equivalent to `!a || !b`, and `!(a || b)` is equivalent to `!a && !b`. This is useful for simplifying complex conditions or avoiding double negatives in code, making logic easier to read and debug.
Key terms
- && operator
- Logical AND; true only if both operands are true.
- || operator
- Logical OR; true if at least one operand is true.
- ! operator
- Logical NOT; reverses a boolean value (true ↔ false).
- Short-circuit evaluation
- Java stops evaluating a compound expression as soon as the result is known, skipping unnecessary checks.
- De Morgan's Laws
- !(a && b) = !a || !b, and !(a || b) = !a && !b — used to simplify negated compound expressions.
Try an AP-style question
Code
int x = 0;
if (x != 0 && 10 / x > 1)
System.out.print("yes");
else
System.out.print("no");What is printed?
- no
- An ArithmeticException
- Nothing
- yes
Show the answer
A. Short-circuit: 10 / x never runs.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 2.5 free in APrep