What to practice
- Evaluate compound boolean expressions using operator precedence (!, &&, ||) and truth tables.
- Apply De Morgan's Laws to simplify negated boolean expressions.
- Trace multi-branch if / else if / else statements and guard conditions using short-circuit evaluation.
Current CED topics: 2.2, 2.3, 2.4, 2.5, 2.6
Current learning objectives: 2.2.A, 2.3.A, 2.4.A, 2.5.A, 2.6.A
1. Core Concept Instruction
Compound boolean expressions combine relational comparisons (==, !=, <, <=, >, >=) using logical NOT (!), AND (&&), and OR (||), with operator precedence ! highest, then &&, then ||. Java evaluates && and || using short-circuit evaluation from left to right: in (cond1 && cond2), if cond1 is false, cond2 is NEVER evaluated (preventing division-by-zero, NullPointerException, or ArrayIndexOutOfBoundsException in guards like idx >= 0 && idx < arr.length && arr[idx] == target). De Morgan's Laws state that negating a conjunction flips && to || and negates each operand: !(A && B) is equivalent to !A || !B, and !(A || B) is equivalent to !A && !B. When negating relational operators, remember to flip strict inequality to inclusive inequality: !(x > 5) is (x <= 5), and !(x <= 10) is (x > 10).
2. Worked Examples
Worked De Morgan's Law Equivalence & Dangling-Else Trace
(a) Simplify !(x >= 4 && (y < 10 || x == 0)) using De Morgan's Laws. (b) Given int n = 15, trace what prints in: if (n > 10) if (n % 2 == 0) System.out.print("A"); else System.out.print("B");
- Step 1 (Apply Outer De Morgan's Law): Distribute ! across the outer && and flip && to ||: !(x >= 4) || !(y < 10 || x == 0).
- Step 2 (Apply Inner De Morgan's Law & Negate Relational Operators): !(x >= 4) becomes (x < 4), and !(y < 10 || x == 0) becomes (!(y < 10) && !(x == 0)), which simplifies to (y >= 10 && x != 0). Final expression: x < 4 || (y >= 10 && x != 0).
- Step 3 (Trace Dangling Else Rule): In Java, an else clause without braces always pairs with the nearest preceding unmatched if (here, the inner if (n % 2 == 0)), regardless of indentation.
- Step 4 (Evaluate for n = 15): Since n > 10 (15 > 10) is true, Java enters the outer if and checks n % 2 == 0 (15 % 2 == 0), which is false, so the inner else executes and prints "B".
Result:
Nested if / else-if Multi-Way Selection & Dangling-Else Resolution
Trace the String assigned to tier when credits = 45 and gpa = 3.6:
String tier = "Standard";
if (credits >= 60) {
tier = "Senior";
} else if (credits >= 30 && gpa >= 3.5) {
tier = "Honors";
} else if (credits >= 30) {
tier = "Sophomore";
}
- Step 1 (Test first branch): credits >= 60 is 45 >= 60 (false).
- Step 2 (Test second branch): credits >= 30 (true) && gpa >= 3.5 (true) is true, assigning tier = "Honors" and skipping the remaining else-if branch.
Result: tier = "Honors"