TOPIC 2.5 · STUDY

Compound Boolean Expressions

Compound boolean expressions combine boolean values with &&, ||, and !. && is true only when both operands are true. || is true when at least one operand is true. ! flips a boolean and is applied before && and ||. Short-circuit evaluation can skip the right operand.

2.5.A

Compound boolean expressions

A compound boolean expression joins boolean operands with && (and), || (or), or ! (not). The result is still a boolean. Use these operators when a decision needs more than one true/false check.

&& is true only when both operands are true. If either side is false, the whole && expression is false. || is true when at least one operand is true. It is false only when both sides are false. ! flips a single boolean: !true is false, and !false is true.

Left Right Left && Right Left || Right
true true true true
true false false true
false true false true
false false false false
boolean sunny = true;
boolean open = false;
boolean picnic = sunny && open;
// picnic is false

boolean hungry = false;
boolean snack = true;
boolean eat = hungry || snack;
// eat is true

boolean packed = true;
System.out.print(!packed);
// prints false

sunny && open needs both flags true, so a closed picnic site keeps picnic false even though sunny is true. hungry || snack needs only one true side, so a ready snack makes eat true. !packed flips true to false before anything else uses that value.

calm true and staffed false combine with && into false. Two inputs feed one and-gate result.

Both operands must be true for &&. One false input forces the compound result to false.

Java applies ! before &&, and && before ||. Write parentheses when you want a different grouping. Without them, an expression such as !flag || ready && late is treated as (!flag) || (ready && late).

boolean flag = false;
boolean ready = true;
boolean late = false;
boolean go = !flag || ready && late;
// grouped as (!flag) || (ready && late)
// !flag is true; ready && late is false
// go is true

Short-circuit evaluation can skip the right operand. For &&, if the left operand is already false, the right operand is not evaluated. For ||, if the left operand is already true, the right operand is not evaluated. That rule matters when the right side has a method call or a division that would fail.

int seats = 0;
boolean safe = (seats > 0) && (40 / seats < 10);
// seats > 0 is false, so && skips 40 / seats
// safe is false; no ArithmeticException

boolean online = true;
boolean pinged = online || (seats / 2 > 0);
// online is true, so || skips the right side
// pinged is true

Key points

  • && is true only when both operands are true.
  • || is true when at least one operand is true.
  • ! flips a boolean value.
  • Precedence order is !, then &&, then ||.
  • && skips the right side when the left is false.
  • || skips the right side when the left is true.

! is applied before && and ||. So !a && b means (!a) && b, not !(a && b).

Practice this topic