ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.5

Compound Boolean Expressions

Skill 2.ASkill 3.A

Big idea: && (and), || (or), and ! (not) combine conditions. Java stops evaluating as soon as it knows the answer, which you can use to avoid crashes.

Learning objectives
  • Develop code to represent compound Boolean expressions and determine the result of these expressions.

The logical operators

Precedence: ! first, then &&, then ||. So a || b && c means a || (b && c).

aba && ba || b!a
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue

Ranges

To test whether a value is in a range, you need two comparisons joined by &&. Math notation like 1 <= x <= 10 does not compile.

Code
int x = 12;
System.out.println(x >= 1 && x <= 10);
System.out.println(x < 1 || x > 10);
System.out.println(!(x > 10));
Output
false
true
false

Short-circuit evaluation

If the left side of && is false, the whole thing is false, so Java skips the right side. If the left side of || is true, Java skips the right side. Put the safety check on the left.

Code
int count = 0;
int total = 50;
if (count != 0 && total / count > 10) {
  System.out.println("high average");
} else {
  System.out.println("no division happened");
}
String s = null;
System.out.println(s == null || s.length() == 0);
Output
no division happened
true
Key points
  • a && b is true only when both are true. a || b is true when at least one is true.
  • Precedence: !, then &&, then ||.
  • Short-circuit: false && … and true || … skip the right side.
Watch out
  • Use short-circuiting to guard against division by zero and NullPointerException; the guard must come first.
  • a || b && c means a || (b && c).
Exam tip
  • If a question's code could crash, check whether short-circuiting prevents the crash before choosing an exception answer.
Quick check
Does this throw? int d = 0; boolean ok = d == 0 || 10 / d > 1;
Show answer
No. d == 0 is true, so the right side of || is never evaluated.
Evaluate with a = true, b = false, c = false: a || b && c
Show answer
true. b && c is false, then true || false is true.