Topic 2.5 — Compound Boolean Expressions

Goal: build compound boolean expressions using &&, ||, and !, and trace how these expressions control decisions in code.

The big idea

A compound boolean expression combines simpler boolean expressions into a bigger one. This lets you represent real rules like: “You can enter if you have a ticket and you’re on the guest list.”

Tools: && (AND), || (OR), ! (NOT)

Basic meanings

Operator Reads as True when…
&& AND both sides are true
|| OR at least one side is true
! NOT it flips true ↔ false

Building compound conditions (examples)

// In a range:
(x >= 10) && (x <= 20)

// Outside a range:
(x < 10) || (x > 20)

// Not equal:
!(x == 5)   // same idea as (x != 5)

Parentheses help (and avoid mistakes)

Operator precedence is ! first, then &&, then ||. Parentheses make your intention clear.

// Clear:
if ((a && b) || c) { ... }

// Without parentheses, Java treats it as:
if ((a && b) || c) { ... }  // because && happens before ||

Short-circuiting (why it matters)

Java may skip evaluating the right side:

  • false && something → right side not evaluated
  • true || something → right side not evaluated
// Safe divide check (right side only runs if x != 0):
if ((x != 0) && (10 / x > 2)) {
  ...
}

Common mistakes

  • Forgetting parentheses and getting a different meaning than intended.
  • Using && when you meant || (or vice versa).
  • Negating incorrectly (misusing !).

Exam mindset

  • Rewrite the condition in English (“and/or/not”) to check if it matches the rule.
  • Use parentheses when mixing && and ||.
  • Remember short-circuiting can prevent errors and affects tracing.

Quick self-check

  1. Write a condition: “x is between 1 and 100 inclusive.”
  2. Write a condition: “x is NOT between 1 and 100.”
  3. Evaluate: (true || false) && false
  4. What is the precedence order among !, &&, and ||?
  5. Why can short-circuiting be useful?

← Back to Unit 2 topics