Lesson 6: Nested Conditionals and De Morgan's Laws
Real decisions are rarely a single test, and Java lets you nest conditionals inside one another to handle layered rules. A nested if is an if statement inside the branch of another, and it is the natural way to express conditions such as 'if the student is a senior and has passed all courses, then ...'. Nesting is powerful but it is also where code becomes hard to read, so the first rule is to keep nesting shallow: if you find yourself three levels deep, consider whether a boolean variable or a helper method would express the logic more clearly.
The else in a nested conditional always pairs with the nearest unmatched if, a rule known as the dangling else, and it is a classic source of bugs. The code if (a) if (b) x(); else y(); runs y() when a is true and b is false — not when a is false — because the else belongs to the inner if. Braces remove all doubt, and you should always use them with nested conditionals, however obvious the pairing seems. When tracing nested conditionals, indent the code mentally and follow one path at a time, writing down which conditions were true at each level.
De Morgan's laws let you rewrite a negated compound condition, and they are the key to simplifying complex logic. The laws say that !(a && b) is equivalent to !a || !b, and !(a || b) is equivalent to !a && !b: negating an 'and' gives an 'or' of the negations, and negating an 'or' gives an 'and' of the negations. They are useful whenever a condition is written as a negation of a compound test, which happens often in guard clauses and in loop conditions. To verify an application, test it with a small truth table — the four combinations of a and b — and confirm both sides agree in every row.
A common use of De Morgan's laws is in writing the opposite of a condition. If a loop should continue while x is between 0 and 100, the condition to stop is the negation: !(x >= 0 && x <= 100), which by De Morgan's laws is x < 0 || x > 100. Writing the negated form directly is often clearer, and it is less error-prone than trying to flip each comparison by hand while remembering to change the operator. When you simplify a condition, do it in two steps: apply De Morgan's laws first, then simplify the individual negations, such as turning !(x < 5) into x >= 5.
When a condition grows complicated, give it a name. Storing a boolean expression in a well-named variable, such as boolean isEligible = age >= 18 && hasTicket;, makes the code read like a sentence and lets you reuse the result without repeating the test. It also makes the logic easier to check: you can print the variable while debugging, or test it separately. Boolean variables combine with the same operators as boolean expressions, so you can build a complex decision from named parts, each of which is simple on its own. If you find yourself writing the same compound condition twice, that is a sign it deserves a name of its own.
A worked example
Worked example: a cinema charges a discount when a customer is a student or a senior, but not when the film is a premiere. The first version nests the tests; the second uses De Morgan's laws to write the same rule as a single condition. Both are correct, and the second is easier to check.
boolean discount;
if (isPremiere)
{
discount = false;
}
else if (isStudent || isSenior)
{
discount = true;
}
else
{
discount = false;
}
// equivalent single condition:
boolean discount2 = !isPremiere && (isStudent || isSenior);
The nested version tests the premiere first, because it overrides everything else, and only then tests student or senior status. The single-condition version says the same thing: not a premiere, and a student or a senior. The negation of the discount condition would be isPremiere || (!isStudent && !isSenior), by De Morgan's laws applied to the 'and' of !isPremiere and (isStudent || isSenior). In free-response answers, choose the form that makes the logic clearest, and test it with one example from each branch.
Key Terms
- Nested conditional
- An if statement inside the branch of another if statement.
- Dangling else
- The rule that an else pairs with the nearest unmatched if.
- De Morgan's laws
- !(a && b) is !a || !b, and !(a || b) is !a && !b.
- Guard clause
- A condition at the start of a block that handles a special case before the main logic.
- Truth table
- A table listing all combinations of boolean inputs and the resulting value of an expression.
Discussion Questions
- Why does an else pair with the nearest if, and how do braces change that?
- When would you replace a nested conditional with a single boolean expression?
- How can a truth table prove that two boolean expressions are equivalent?
Practice Questions
- Rewrite !(a && b) using De Morgan's laws.
- Rewrite !(x < 5 || y > 10) without the outer negation.
- if (a) { if (b) { System.out.print(1); } else { System.out.print(2); } } What prints when a is true and b is false?
- Write a condition that is true when n is NOT between 1 and 10 inclusive.
- Simplify !(!(p)) and explain.
Show answers
- !a || !b
- x >= 5 && y <= 10
- 2, because the else belongs to the inner if.
- n < 1 || n > 10
- p, because negating twice returns the original value.