Boolean Expressions and De Morgan's Laws
AP Computer Science A · Unit 2 — Selection and Iteration
Boolean expressions
A boolean expression evaluates to exactly one of two values, true or false. Relational operators build them from numbers: <, <=, >, >=, ==, !=. Logical operators combine them: && (and), || (or), ! (not).
Short-circuit evaluation
Java evaluates && and || from left to right and stops as soon as the answer is known. In p && q the operand q is evaluated only when p is true; in p || q the operand q is evaluated only when p is false. That is why the guard s.length() > 0 && s.substring(0, 1).equals("A") is safe on an empty string while the same two operands written in the other order throw an exception.
De Morgan's Laws
!(p && q) is equivalent to !p || !q, and !(p || q) is equivalent to !p && !q. Negating a relational operator moves it across the boundary rather than past it: the negation of x < 5 is x >= 5, never x > 5. Two boolean expressions are equivalent when they agree on every row of the truth table, and that table is the only proof the exam accepts.
x = 5 does not satisfy x < 5, so it must fall in the negated part.Worked example: remove the outer negation
Rewrite the following expression so that no outer negation remains, then state in plain English what the new condition says.
!(age >= 13 && age < 65)
Solution
Step 1 — De Morgan. The negation wraps around an &&, so it turns into || and is distributed over the two sides:
!(age >= 13) || !(age < 65)
Step 2 — negate each comparison. The negation of >= is <; the negation of < is >=:
age < 13 || age >= 65
Read it as a sentence: "under 13 years old, or 65 years old and above". The two cutoffs 13 and 65 stay exactly where they were — only the side changes.
Quick self-check: substitute the values 12, 13, 64, 65 into both expressions. These four numbers are the four points right at the boundaries; if the two expressions agree on all four, it is almost certainly correct.
Common mistake
The costliest error: negatingx < 5 into x > 5, dropping the value x = 5. With real data, this error shows up in exactly one case, so a quick test run will not catch it. How to prevent it: each time you negate a comparison, write down the value right at the boundary and substitute it into both expressions — if the two sides give different results, you have just dropped the boundary.Key takeaway
An outer! around && becomes ||, and vice versa. Negating a comparison flips the sign and keeps the boundary. The order of the two sides of && is where you place the guard, so do not swap them.