ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.6

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.

Learning objectives
  • 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.

ExpressionEquivalent
!(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.

Code
boolean[] vals = {true, false};
for (boolean a : vals) {
  for (boolean b : vals) {
    System.out.println((!(a && b)) == (!a || !b));
  }
}
Output
true
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.

Code
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);
Output
true
true
true
Key points
  • 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 with null to see if a reference points to an object.
  • Classes often define equals to compare by attributes.
Watch out
  • When negating, flip each relational operator too: !(x > 0) is x <= 0, not x < 0.
Exam tip
  • To check two choices for equivalence fast, try one value that makes the original true and one that makes it false.
Quick check
Simplify !(age < 13 || age > 19).
Show answer
age >= 13 && age <= 19.
Not on the exam
  • Overriding the equals method.