AP Computer Science A · Study guide

Compound Boolean Expressions

AP® Computer Science A · Selection and Iteration

Compound Boolean Expressions

Combining conditions with ! (not), && (and), and || (or): what each operator produces, the order in which they are evaluated, how they express ranges, and how short-circuit evaluation skips work and prevents errors.

Big Picture

Many decisions depend on more than one fact: a teen ticket requires an age of at least 13 and at most 19; a weather alert fires if it is too cold or too hot. The logical operators ! (not), && (and), and || (or) combine Boolean expressions into compound ones. Their order of precedence is !, then &&, then ||, and an expression involving logical operators evaluates to a Boolean value. Short-circuit evaluation means that when the first operand of && or || already determines the result, the second is not evaluated.

1Combining Conditions

Relational operators compare two values and produce a single true or false. Logical operators take Boolean values and combine them. Logical operators ! (not), && (and), and || (or) are used with Boolean expressions, which may be comparisons, boolean variables, or method calls that return boolean.

The result of a compound expression is itself a Boolean value, so it can be stored, printed, returned from a method, or used as the condition of an if. Compound expressions let a single condition capture a rule that would otherwise need nested if statements, which often makes code shorter and easier to read.

Translating a rule from words into a compound expression is a skill worth practicing. "Free entry for members or for children under 12" becomes isMember || age < 12. "Open on weekdays between 9 and 17" becomes isWeekday && hour >= 9 && hour < 17. Listing the individual conditions first, then deciding whether all of them are required (&&) or any one is enough (||), keeps the translation accurate.

OperatorNameResult is true whenExample (x = 15)
!anota is false!(x > 20) is true
a && bandBoth a and b are truex > 10 && x < 20 is true
a || bora is true, b is true, or bothx < 0 || x > 12 is true
Worked Example 1 The three operators

Evaluating !, &&, and ||

Predict each value.

Code
boolean a = true;
boolean b = false;
System.out.println(!a);
System.out.println(a && b);
System.out.println(a || b);
System.out.println(!b && a);
Output
false
false
true
true
  1. 1!a. a is true, so !a is false.
  2. 2a && b. Not both are true: false.
  3. 3a || b. At least one is true: true.
  4. 4!b && a. !b is true and a is true: true.
Result: The output is false, false, true, true. Logical operators combine Boolean values, and the result is always another Boolean value.

2and, or, not

The expression !a evaluates to true if a is false and evaluates to false otherwise. The expression a && b evaluates to true if both a and b are true and evaluates to false otherwise. The expression a || b evaluates to true if a is true, b is true, or both, and evaluates to false otherwise.

A truth table lists the result for every combination of inputs. For two Boolean values there are only four combinations, so each operator can be described completely in a small grid. Note that Java's "or" is inclusive: a || b is true when both are true, unlike the everyday "either one or the other, but not both."

Truth tables are also a practical tool for checking your own expressions. When a condition combines two or three Boolean parts, write a row for every combination of their values and work out what the expression gives in each row. Comparing those results with what the rule should produce shows immediately whether the expression is right, and which row exposes the problem if it is not.

Figure 1. a && b is true only if both are true; a || b is true if either one, or both, is true.
Common Mistake 1 · Reading || as "Exactly One"

true || true is true. The || operator requires at least one operand to be true; it does not exclude the case where both are. When tracing, do not turn a true result into false just because both sides hold.

3Expressing Ranges

The most common compound conditions describe ranges. "x is between 10 and 20, inclusive" becomes x >= 10 && x <= 20: both comparisons must hold, which describes the values inside the interval. "x is outside that range" becomes x < 10 || x > 20: either comparison is enough, which describes the two pieces outside.

Each side of && or || must be a complete Boolean expression. The mathematical shorthand 10 <= x <= 20 and the spoken shorthand x > 10 && < 20 both fail to compile. Write the variable in each comparison, and check whether each boundary should be included.

The two forms are opposites. Every value is either inside the interval, where the && expression is true, or outside it, where the || expression is true, and never both. Notice how the operators flip: >= becomes <, <= becomes >, and && becomes ||. That pattern is a preview of the rules for building equivalent Boolean expressions.

Figure 2. && describes values inside a range: both conditions must hold. || describes values outside it: either condition is enough.
Worked Example 2 Inside a range

Testing a Range With &&

A teen ticket applies to ages 13 through 19. Predict the output.

Code
public static boolean isTeen(int age)
{
    return age >= 13 && age <= 19;
}
Output
false
true
true
false
  1. 112. 12 >= 13 is false, so the whole expression is false.
  2. 213 and 19. Both comparisons are true at the boundaries, because >= and <= include them.
  3. 320. 20 <= 19 is false.
Result: The output is false, true, true, false. A range check needs two comparisons joined by &&, and a method can return the Boolean result directly.
Worked Example 3 Outside a range

Testing for Extremes With ||

A sensor flags temperatures below 0 or above 35. Predict the output.

Code
int[] readings = {-4, 0, 22, 35, 41};
int t0 = -4;
int t1 = 22;
int t2 = 41;
System.out.println(t0 < 0 || t0 > 35);
System.out.println(t1 < 0 || t1 > 35);
System.out.println(t2 < 0 || t2 > 35);
System.out.println(0 < 0 || 0 > 35);
Output
true
false
true
false
  1. 1−4. The first comparison is true, which is enough for ||.
  2. 222. Neither comparison is true: false.
  3. 341. The second comparison is true.
  4. 40. 0 < 0 is false and 0 > 35 is false: the boundary is not flagged.
Result: The output is true, false, true, false. || describes values outside a range: satisfying either condition is enough.
Worked Example 4 Incomplete comparisons

Each Side Must Be a Full Comparison

Explain the compile error.

Code that does not compile
int x = 15;
boolean inRange = x > 10 && < 20;
  1. 1< 20 is not an expression. Each operand of && must be a complete Boolean expression; the left side of the second comparison is missing.
  2. 2Fix. Repeat the variable: x > 10 && x < 20.
Result: The compiler rejects the statement (javac reports an "illegal start of type" at the stray <). Unlike everyday speech, Java requires both comparisons to be written out in full.

4Order of Precedence

The order of precedence for evaluating logical operators is ! (not), && (and), then || (or). In a || b && !c, Java first negates c, then evaluates the &&, and finally the ||. All of the logical operators have lower precedence than the relational operators, so x > 10 && x < 20 compares first and combines second, exactly as intended.

The ! operator applies only to the operand immediately after it. !a || b negates only a; to negate a whole expression, put it in parentheses: !(a || b). Parentheses are the clearest way to show the intended grouping, and they are never wrong when they match what you mean.

Figure 3. The order of precedence for evaluating logical operators is ! (not), && (and), then || (or). Parentheses override it.
StepExpression (a = false, b = true, c = false)Rule
1a || b && !cStart
2false || true && true! first: !c is true
3false || true&& next: true && true
4true|| last
Worked Example 5 Precedence

Without and With Parentheses

Predict each value.

Code
boolean a = true;
boolean b = false;
boolean c = false;
System.out.println(a || b && c);
System.out.println((a || b) && c);
System.out.println(!a || b);
System.out.println(!(a || b));
Output
true
false
false
false
  1. 1a || b && c. && first: b && c is false; then true || false is true.
  2. 2(a || b) && c. Parentheses first: true; then true && false is false.
  3. 3!a || b. ! applies only to a: false || false is false.
  4. 4!(a || b). a || b is true, and its negation is false.
Result: The output is true, false, false, false. Precedence is !, then &&, then ||; use parentheses to make the intended grouping explicit.
Common Mistake 2 · Applying ! to a Number Comparison Without Parentheses

!x > 5 does not compile when x is an int, because ! binds to x first and cannot apply to a number. Write !(x > 5), or more simply x <= 5.

5Short-Circuit Evaluation

Short-circuit evaluation occurs when the result of a logical operation using && or || can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated. If the left side of && is false, the whole expression must be false; if the left side of || is true, the whole expression must be true.

Short-circuiting is more than a speed-up. It lets a condition guard against errors: in count != 0 && total / count > 2, the division is attempted only when count is not zero, and in s != null && s.length() > 3, length is called only when there is a string. The order matters: the guard must be on the left.

Figure 4. Short-circuit evaluation: when the first operand of && is false, or the first operand of || is true, the second operand is not evaluated.
OperatorFirst operandSecond operand evaluated?Result
&&falseNofalse
&&trueYesthe second operand's value
||trueNotrue
||falseYesthe second operand's value
Worked Example 6 Short-circuit evaluation

Watching Which Operands Run

The method check prints a message each time it is evaluated. Predict the exact output.

Code
public static boolean check(String label, boolean value)
{
    System.out.println("evaluating " + label);
    return value;
}
Output
evaluating A
false
evaluating C
true
evaluating E
evaluating F
false
  1. 1A && B. A is false, so && is already false; B is never evaluated.
  2. 2C || D. C is true, so || is already true; D is never evaluated.
  3. 3E && F. E is true, which does not settle &&, so F must be evaluated: false.
Result: B and D are never evaluated. Short-circuit evaluation skips the second operand whenever the first one already determines the result.
Worked Example 7 Guarding with short-circuit

Avoiding Division by Zero

An average should be reported as high only if there is at least one item. Compare the two orders.

Guard first
int count = 0;
int total = 10;
if (count != 0 && total / count > 2)
{
    System.out.println("high average");
}
else
{
    System.out.println("no high average");
}
Output
no high average
Guard second
int count = 0;
int total = 10;
if (total / count > 2 && count != 0)
{
    System.out.println("high average");
}
  1. 1Guard first. count != 0 is false, so && stops; the division never happens.
  2. 2Guard second. The division is evaluated first, and dividing an int by 0 throws an ArithmeticException before the guard is ever checked.
Result: The first version prints no high average; the second stops with an ArithmeticException. Put the safety check on the left of && so short-circuiting protects the risky operand.
Worked Example 8 Guarding against null

Short-Circuiting Before a Method Call

Predict the output.

Code
String code = null;
System.out.println(code != null && code.length() == 4);
System.out.println(code == null || code.length() == 0);
code = "A7K2";
System.out.println(code != null && code.length() == 4);
System.out.println(code == null || code.length() == 0);
Output
false
true
true
false
  1. 1Line 2. code != null is false, so && stops and length() is never called on null.
  2. 2Line 3. code == null is true, so || stops: the "missing" check is true without calling length().
  3. 3After assigning "A7K2". Both left sides now let evaluation continue: the length is 4, so the first check is true and the "missing" check is false.
Result: The output is false, true, true, false, with no NullPointerException. A null check on the left of && or || makes the method call on the right safe.
Common Mistake 3 · Putting the Guard on the Right

total / count > 2 && count != 0 divides before it checks, so a count of 0 still throws an ArithmeticException. Short-circuiting only protects operands to the right of the deciding one. Place the check that makes the rest safe first.

6Writing Compound Conditions Well

Compound conditions can grow hard to read. Keep each one focused on a single rule, use parentheses to show grouping even where precedence would give the same answer, and consider storing parts in well-named boolean variables: boolean isTeen = age >= 13 && age <= 19; followed by if (isTeen && hasPass) reads almost like English.

When tracing a compound condition, evaluate it in the same order Java does: relational comparisons first, then !, then &&, then ||, stopping early whenever short-circuiting applies. Writing each intermediate value down, as in the step table above, prevents most mistakes.

Common Mistake 4 · Mixing && and || Without Parentheses

member || age < 12 && weekday is evaluated as member || (age < 12 && weekday). If the intended rule was "(member or child) on a weekday," the grouping must be written explicitly: (member || age < 12) && weekday.

Four Habits for Compound Conditions

1. && Both, || Either

|| is also true when both sides are true.

2. Full Comparisons

x > 10 && x < 20, never x > 10 && < 20.

3. ! then && then ||

Use parentheses to make grouping explicit.

4. Guard on the Left

Short-circuiting protects only what comes after.

Core Synthesis

Logical operators ! (not), && (and), and || (or) are used with Boolean expressions. !a is true if a is false; a && b is true if both are true; a || b is true if a is true, b is true, or both. The order of precedence is !, &&, then ||, and an expression involving logical operators evaluates to a Boolean value. Short-circuit evaluation occurs when the result of && or || can be determined by evaluating only the first Boolean expression; in that case, the second is not evaluated.