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.
- 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).
| a | b | a && b | a || b | !a |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
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.
int x = 12;
System.out.println(x >= 1 && x <= 10);
System.out.println(x < 1 || x > 10);
System.out.println(!(x > 10));Outputfalse 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.
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);Outputno division happened true
a && bis true only when both are true.a || bis true when at least one is true.- Precedence:
!, then&&, then||. - Short-circuit:
false && …andtrue || …skip the right side.
- Use short-circuiting to guard against division by zero and
NullPointerException; the guard must come first. a || b && cmeansa || (b && c).
- If a question's code could crash, check whether short-circuiting prevents the crash before choosing an exception answer.
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.