Unit 2 Cycle 2 Day 1: Nested If vs Compound Boolean

Unit 2 Advanced (Cycle 2) Day 1 of 28 Advanced

Nested If vs Compound Boolean

Section 2.5 — Compound Boolean

Key Concept

A nested if inside another if can always be rewritten as a single if with a compound boolean using &&. The code if (a) { if (b) { ... } } is equivalent to if (a && b) { ... }. However, when else branches are involved, the equivalence becomes more complex. A nested structure allows different else actions for each level, while a compound condition has a single else for the entire expression. The AP exam tests whether two code segments produce identical results.

Consider the following two code segments.

// Segment A if (x > 0) { if (x < 100) { System.out.print("valid"); } } // Segment B if (x > 0 && x < 100) { System.out.print("valid"); }

For which values of x do Segments A and B produce different output?

Answer: (D) They always produce the same output.

Nested ifs with no else are logically equivalent to a compound AND. Segment A checks x > 0 then x < 100. Segment B checks both simultaneously. Both print "valid" only when 0 < x < 100.

Why Not the Others?

(A) Both segments print "valid" when x=50 (0 < 50 < 100).

(B) Neither segment prints anything when x=0 (0 is not > 0).

(C) Neither prints when x=100 (100 is not < 100).

Common Mistake

Nested ifs (without else) are equivalent to &&. However, adding an else to the nested version makes them behave differently. The equivalence only holds when there are no else branches.

AP Exam Tip

On the AP exam, expect questions asking you to identify equivalent code. Nested ifs without else = AND. But nested ifs with else create more complex branching.

Review this topic: Section 2.5 — Compound Boolean • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.