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.
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.
| Operator | Name | Result is true when | Example (x = 15) |
|---|---|---|---|
!a | not | a is false | !(x > 20) is true |
a && b | and | Both a and b are true | x > 10 && x < 20 is true |
a || b | or | a is true, b is true, or both | x < 0 || x > 12 is true |
Evaluating !, &&, and ||
Predict each value.
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);
false
false
true
true
- 1
!a.aistrue, so!aisfalse. - 2
a && b. Not both aretrue:false. - 3
a || b. At least one istrue:true. - 4
!b && a.!bistrueandaistrue:true.
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.
a && b is true only if both are true; a || b is true if either one, or both, is true.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.
&& describes values inside a range: both conditions must hold. || describes values outside it: either condition is enough.Testing a Range With &&
A teen ticket applies to ages 13 through 19. Predict the output.
public static boolean isTeen(int age)
{
return age >= 13 && age <= 19;
}
false
true
true
false
- 112.
12 >= 13isfalse, so the whole expression isfalse. - 213 and 19. Both comparisons are
trueat the boundaries, because>=and<=include them. - 320.
20 <= 19isfalse.
&&, and a method can return the Boolean result directly.Testing for Extremes With ||
A sensor flags temperatures below 0 or above 35. Predict the output.
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);
true
false
true
false
- 1−4. The first comparison is
true, which is enough for||. - 222. Neither comparison is
true:false. - 341. The second comparison is
true. - 40.
0 < 0isfalseand0 > 35isfalse: the boundary is not flagged.
|| describes values outside a range: satisfying either condition is enough.Each Side Must Be a Full Comparison
Explain the compile error.
int x = 15;
boolean inRange = x > 10 && < 20;
- 1
< 20is not an expression. Each operand of&&must be a complete Boolean expression; the left side of the second comparison is missing. - 2Fix. Repeat the variable:
x > 10 && x < 20.
<). 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.
! (not), && (and), then || (or). Parentheses override it.| Step | Expression (a = false, b = true, c = false) | Rule |
|---|---|---|
| 1 | a || b && !c | Start |
| 2 | false || true && true | ! first: !c is true |
| 3 | false || true | && next: true && true |
| 4 | true | || last |
Without and With Parentheses
Predict each value.
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));
true
false
false
false
- 1
a || b && c.&&first:b && cisfalse; thentrue || falseistrue. - 2
(a || b) && c. Parentheses first:true; thentrue && falseisfalse. - 3
!a || b.!applies only toa:false || falseisfalse. - 4
!(a || b).a || bistrue, and its negation isfalse.
!, then &&, then ||; use parentheses to make the intended grouping explicit.!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.
&& is false, or the first operand of || is true, the second operand is not evaluated.| Operator | First operand | Second operand evaluated? | Result |
|---|---|---|---|
&& | false | No | false |
&& | true | Yes | the second operand's value |
|| | true | No | true |
|| | false | Yes | the second operand's value |
Watching Which Operands Run
The method check prints a message each time it is evaluated. Predict the exact output.
public static boolean check(String label, boolean value)
{
System.out.println("evaluating " + label);
return value;
}
evaluating A
false
evaluating C
true
evaluating E
evaluating F
false
- 1A && B. A is
false, so&&is alreadyfalse; B is never evaluated. - 2C || D. C is
true, so||is alreadytrue; D is never evaluated. - 3E && F. E is
true, which does not settle&&, so F must be evaluated:false.
Avoiding Division by Zero
An average should be reported as high only if there is at least one item. Compare the two orders.
int count = 0;
int total = 10;
if (count != 0 && total / count > 2)
{
System.out.println("high average");
}
else
{
System.out.println("no high average");
}
no high average
int count = 0;
int total = 10;
if (total / count > 2 && count != 0)
{
System.out.println("high average");
}
- 1Guard first.
count != 0isfalse, so&&stops; the division never happens. - 2Guard second. The division is evaluated first, and dividing an
intby 0 throws anArithmeticExceptionbefore the guard is ever checked.
ArithmeticException. Put the safety check on the left of && so short-circuiting protects the risky operand.Short-Circuiting Before a Method Call
Predict the output.
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);
false
true
true
false
- 1Line 2.
code != nullisfalse, so&&stops andlength()is never called onnull. - 2Line 3.
code == nullistrue, so||stops: the "missing" check istruewithout callinglength(). - 3After assigning "A7K2". Both left sides now let evaluation continue: the length is 4, so the first check is
trueand the "missing" check isfalse.
NullPointerException. A null check on the left of && or || makes the method call on the right safe.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.
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.
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.