Comparing Boolean Expressions
Skill 2.ASkill 3.A
Big idea: Different-looking conditions can always give the same answer. De Morgan's laws tell you how to push a ! inside parentheses.
- Compare equivalent Boolean expressions.
- Develop code to compare object references using Boolean expressions and determine the result of these expressions.
De Morgan's laws
To negate a compound condition, negate each part and swap the operator.
| Expression | Equivalent |
|---|---|
!(a && b) | !a || !b |
!(a || b) | !a && !b |
!(x > 5) | x <= 5 |
!(x == y) | x != y |
!(x >= 1 && x <= 10) | x < 1 || x > 10 |
Proving equivalence with a truth table
Two expressions are equivalent if they match for every combination of inputs. With two booleans there are only four rows to check.
Codeboolean[] vals = {true, false};
for (boolean a : vals) {
for (boolean b : vals) {
System.out.println((!(a && b)) == (!a || !b));
}
}Outputtrue true true true
Comparing object references
== and != on references ask "same object?" Comparing with null asks "does this variable refer to any object?". Many classes provide an equals method that compares objects by their contents instead.
String a = new String("cat");
String b = new String("cat");
String c = null;
System.out.println(a != b);
System.out.println(a.equals(b));
System.out.println(c == null);Outputtrue true true
- Equivalent expressions give the same value in every case; truth tables prove it.
- De Morgan:
!(a && b)≡!a || !b;!(a || b)≡!a && !b. - Compare references with
==/!=, and withnullto see if a reference points to an object. - Classes often define
equalsto compare by attributes.
- When negating, flip each relational operator too:
!(x > 0)isx <= 0, notx < 0.
- To check two choices for equivalence fast, try one value that makes the original true and one that makes it false.
Simplify !(age < 13 || age > 19).
Show answer
age >= 13 && age <= 19.
- Overriding the equals method.