Skip to content
🎯⭐ INTERACTIVE LESSON

Conditionals & Boolean Logic

Learn step-by-step with interactive practice!

Conditionals & Boolean Logic - Complete Interactive Lesson

Part 1: Core Concepts

🔀 Conditionals (Advanced)

Part 1 of 7 — Nested Ifs, Complex Conditions, and Common Patterns


Nested If Statements

int temp = 75;
boolean isSunny = true;

if (temp > 70) {
    if (isSunny) {
        System.out.println("Go to the beach!");
    } else {
        System.out.println("Stay in and read.");
    }
} else {
    System.out.println("Too cold for outdoor activities.");
}

🔑 Nested ifs create conditions within conditions. The inner if only runs when the outer if is true. Trace these from the outside in.


Equivalent Conditions

Many conditions can be rewritten in different ways:

OriginalEquivalentWhy
if (x > 0) { return true; } else { return false; }return x > 0;The boolean expression IS the result
if (flag == true)if (flag)flag is already boolean
if (flag == false)if (!flag)Negating is cleaner
if (x >= 0 && x <= 100)Range check: 0 to 100Common pattern for bounds checking

Concept Check 🎯

Common Conditional Patterns

1. Finding Min/Max

int max;
if (a > b) {
    max = a;
} else {
    max = b;
}
// Math.max is not on the AP Java Quick Reference: write the comparison yourself

2. Absolute Value

int absVal;
if (x < 0) {
    absVal = -x;
} else {
    absVal = x;
}
// Equivalent: int absVal = Math.abs(x);

3. Clamping a Value

// Keep score between 0 and 100
if (score > 100) {
    score = 100;
} else if (score < 0) {
    score = 0;
}

4. Dangling Else Problem

if (x > 0)
    if (y > 0)
        System.out.println("Both positive");
else
    System.out.println("This is the INNER else!");
// The else matches the NEAREST unmatched if (the inner one)

Applied Recall ✍️

  1. In a dangling else situation, the else always pairs with the _______ unmatched if.

  2. The statement if (flag == true) can be simplified to if (_______).

  3. Math.abs(-7) returns _______.

Simplify the Code 🔍

AP Exam Strategy: Conditionals

  • Trace nested ifs from the outside in — do not skip levels
  • The dangling else is a trick question favorite — else matches the nearest unmatched if
  • Simplify boolean returns: if (cond) return true; else return false; → return cond;
  • Math.abs() is on the AP Java Quick Reference, but Math.max() and Math.min() are not — be ready to write the if/else comparison for a larger or smaller value yourself
  • Watch for conditions that are always true or always false (tautologies/contradictions)
  • Common error: using 1 < x < 100 — Java requires x > 1 && x < 100

AP-Style Application 🎯

Part 2: Multiway Selection: Ordering else-if Chains

🔀 Conditionals (Advanced)

Part 2 of 7 — Multiway Selection: Ordering else-if Chains


CED Topic 2.4 covers multiway selection: an if followed by one or more else if branches and, usually, a final else. Part 1 showed that only the first true branch runs. This part is about the decisions that make a chain correct: the order of the tests, the boundary values, and what happens to values no branch expects.

In this part
How a chain is evaluated
Why the order of the tests matters
Boundary gaps and overlaps
Writing a chain from a table

How a Chain Is Evaluated

int cost;
if (weight <= 8) {
    cost = 5;
} else if (weight <= 32) {
    cost = 9;
} else if (weight <= 160) {
    cost = 15;
} else {
    cost = 25;
}

Java tests the conditions from the top. The first true one runs its body, and every remaining test is skipped. The final else runs only when all the tests are false.

Because a branch is reached only after every test above it failed, each test can rely on that. The second test means "more than 8 and at most 32" without saying weight > 8.

weightFirst true testcost
8weight <= 85
9weight <= 329
32weight <= 329
100weight <= 16015
161none, so the else runs25

Order Matters

String grade;
if (score >= 70) {
    grade = "C";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 90) {
    grade = "A";
} else {
    grade = "F";
}

A score of 95 passes the first test and gets "C". Every score that could reach the "B" or "A" branch has already been caught by score >= 70, so those branches are unreachable.

Kind of testCorrect order
>= or > thresholdsLargest threshold first
<= or < thresholdsSmallest threshold first, as in the shipping chain

Concept Check 🎯

Boundary Gaps and Overlaps

Specification: below 60 degrees is "cold", 60 through 80 is "mild", and above 80 is "hot".

String label;
if (temp < 60) {
    label = "cold";
} else if (temp > 60 && temp < 80) {
    label = "mild";
} else {
    label = "hot";
}
tempShould beThis code givesProblem
59coldcold
60mildhottemp > 60 leaves a gap at 60
80mildhottemp < 80 leaves a gap at 80
81hothot

The fixed chain is shorter, because the second test can rely on the first one having failed:

if (temp < 60) {
    label = "cold";
} else if (temp <= 80) {
    label = "mild";
} else {
    label = "hot";
}

🔑 Test the boundaries. For every number in a condition, try the number itself and the values just below and just above it. Here that means 59, 60, 61, 79, 80 and 81.

A Chain Without a Final else

Without a final else, it is possible for no branch to run. That is fine when nothing should happen for the leftover values, but it is a bug when every value needs an answer.

Find the Boundary Bug 🔍

Worked Example: Writing a Chain from a Table

Distance (miles)Zone
50 or less1
51 to 3002
301 to 10003
more than 10004

Version 1: smallest threshold first, with <=.

public static int zone(int miles) {
    if (miles <= 50) {
        return 1;
    } else if (miles <= 300) {
        return 2;
    } else if (miles <= 1000) {
        return 3;
    } else {
        return 4;
    }
}

Version 2: largest threshold first, with >.

public static int zone(int miles) {
    if (miles > 1000) {
        return 4;
    } else if (miles > 300) {
        return 3;
    } else if (miles > 50) {
        return 2;
    } else {
        return 1;
    }
}

Both versions are correct. Check them at every boundary:

miles505130030110001001
Zone122334

🎯 AP Connection: A free-response method that returns a category is usually scored on its boundaries. Write out the boundary table before you write the chain.

Applied Recall ✍️

  1. What does zone(300) return?

  2. What does zone(1001) return?

  3. In the shipping chain, what is cost when weight is 33?

AP-Style Application 🎯

Each segment should print "low" for n below 10, "mid" for 10 through 99, and "high" for 100 or more.

Segment I

if (n < 10) { System.out.print("low"); }
else if (n < 100) { System.out.print("mid"); }
else { System.out.print("high"); }

Segment II

if (n >= 100) { System.out.print("high"); }
else if (n >= 10) { System.out.print("mid"); }
else { System.out.print("low"); }

Segment III

if (n < 100) { System.out.print("mid"); }
else if (n < 10) { System.out.print("low"); }
else { System.out.print("high"); }

Segment IV

if (x > 10) { System.out.print("A"); }
else if (x > 20) { System.out.print("B"); }
else if (x < 5) { System.out.print("C"); }
else { System.out.print("D"); }

Part 3: Nested Decisions and Their Compound Equivalents

🔀 Conditionals (Advanced)

Part 3 of 7 — Nested Decisions and Their Compound Equivalents


A nested if statement is an if inside the body of another if (CED Topic 2.4). Nesting lets one decision depend on another. This part traces nested decisions path by path, shows when nesting can be rewritten with &&, and builds a classic exam method: the largest of three values.

In this part
Nested ifs as decision trees
Nesting vs. &&
Using braces to control which if an else belongs to
Largest of three, two ways, and a tie bug

Nested ifs as Decision Trees

int discount;
if (member) {
    if (total >= 50) {
        discount = 10;
    } else {
        discount = 5;
    }
} else {
    if (total >= 100) {
        discount = 5;
    } else {
        discount = 0;
    }
}

Two yes-or-no questions give four paths. List every path with an input that reaches it:

membertotalPathdiscount
true60member, at least 5010
true30member, under 505
false120non-member, at least 1005
false80non-member, under 1000

Nesting vs. &&

When neither if has an else, nesting is the same as &&:

if (a) {
    if (b) {
        System.out.print("X");
    }
}
// same as
if (a && b) {
    System.out.print("X");
}

Once an else is involved, keep track of which condition it belongs to:

if (a) {
    if (b) {
        System.out.print("X");
    } else {
        System.out.print("Y");
    }
}

Y prints only when a is true and b is false. The flat version is if (a && b) {...X...} else if (a) {...Y...}. Writing if (a && b) {...X...} else {...Y...} is not the same, because it also prints Y whenever a is false.

Braces Decide Where an else Belongs

Part 1 showed that, without braces, an else pairs with the nearest unmatched if. To attach it to the outer if, close the inner if with a brace first:

if (x > 0) {
    if (y > 0) {
        System.out.println("both positive");
    }
} else {
    System.out.println("x is not positive");
}

Concept Check 🎯

Worked Example: Largest of Three

Math.max is not on the AP Java Quick Reference, so exam questions expect you to build this with if statements.

Version 1: nested decisions.

int big;
if (a >= b) {
    if (a >= c) {
        big = a;
    } else {
        big = c;
    }
} else {
    if (b >= c) {
        big = b;
    } else {
        big = c;
    }
}
a, b, cPathbig
3, 7, 5a >= b false; b >= c true7
9, 2, 9a >= b true; a >= c true9
4, 4, 6a >= b true; a >= c false6

Version 2: keep a running largest.

int big = a;
if (b > big) {
    big = b;
}
if (c > big) {
    big = c;
}

Here separate ifs are exactly right, because each test compares with the updated big.

A version with a tie bug.

int big;
if (a > b && a > c) {
    big = a;
} else if (b > a && b > c) {
    big = b;
} else {
    big = c;
}

With a = 5, b = 5 and c = 1, neither strict test passes, so big becomes 1. Strict > fails whenever the two largest values tie.

Trace the Versions 🎯

Applied Recall ✍️

  1. In the discount code, what is discount when member is true and total is 50?

  2. In the discount code, what is discount when member is false and total is 99?

  3. Version 1 of largest of three runs with a = 2, b = 2, c = 1. What is big?

Part 3 Summary

IdeaRule
Nested ifsOne path per combination of answers; test an input for each path
No else anywhereif (a) { if (b) ... } is if (a && b)
Inner elseRuns only when the outer test is true and the inner one is false
Outer elseClose the inner if with a brace before the else
Largest of threeNested >= tests, or a running largest with separate ifs
Strict > on tiesTwo equal largest values can fail every test

Next: Part 4 proves when two conditions are equivalent, using truth tables and De Morgan's laws.

Part 4: Truth Tables, De Morgan's Laws, and Equivalence

🔀 Conditionals (Advanced)

Part 4 of 7 — Truth Tables, De Morgan's Laws, and Equivalence


CED Topic 2.6 asks you to decide whether two Boolean expressions are equivalent, meaning they give the same value for every possible input. Part 1 stated De Morgan's laws. This part shows how to check any claimed equivalence with a truth table, how to negate comparisons, and how to disprove a claim with one counterexample.

In this part
Building truth tables
Proving De Morgan's laws
Negating relational operators
Counterexamples, tautologies, and contradictions

Building a Truth Table

A truth table lists every combination of inputs. Two variables give 4 rows, three give 8, and n variables give 2 to the power n.

ABA && BA || B!A
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue

Proving De Morgan's Law

AB!(A && B)!A || !B!A && !B
truetruefalsefalsefalse
truefalsetruetruefalse
falsetruetruetruefalse
falsefalsetruetruetrue

The columns for !(A && B) and !A || !B match on all four rows, so they are equivalent. The last column differs from !(A && B) in two rows, so !A && !B is not equivalent to it. One row where two expressions differ, called a counterexample, is enough to prove they are not equivalent.

Three Variables

ABCA && (B || C)(A && B) || (A && C)A || (B && C)(A || B) && C
TTTTTTT
TTFTTTF
TFTTTTT
TFFFFTF
FTTFFTT
FTFFFFF
FFTFFFF
FFFFFFF

The first pair matches on all 8 rows. The second pair differs in the second row, A true, B true, C false, so moving the parentheses changed the meaning.

Concept Check 🎯

Negating Comparisons

ExpressionIts negation
x < yx >= y
x <= yx > y
x > yx <= y
x >= yx < y
x == yx != y
x != yx == y

The negation of < is >=, not >. The negation must cover every case the original did not, including equality.

De Morgan with Comparisons

Negate each part and swap && with ||:

OriginalStepResult
!(x >= 1 && x <= 10)!(x >= 1) || !(x <= 10)x < 1 || x > 10
!(age < 13 || age > 19)!(age < 13) && !(age > 19)age >= 13 && age <= 19
!(s.equals("y") || n > 5)!s.equals("y") && !(n > 5)!s.equals("y") && n <= 5

Worked Example: Is This Rewrite Correct?

A student replaces the first line with the second:

boolean r1 = !(n > 5 && n < 10);
boolean r2 = n <= 5 && n >= 10;

Try n = 3. r1 is !(false && true), which is true. r2 is true && false, which is false. One counterexample proves the rewrite is wrong. The student negated both parts but forgot to change && to ||, and r2 is now false for every n, because no number is both at most 5 and at least 10.

Expressions with Fixed Values

ExpressionValue for every inputName
x > 5 || x <= 5always truetautology
x > 5 && x <= 5always falsecontradiction
A || (A && B)same as Athe && B part never changes the result
!(!A)same as Adouble negation

Negate and Simplify 🔍

Apply De Morgan 🎯

Applied Recall ✍️

  1. Type the value of !(true && !false).

  2. In a two-variable truth table, in how many rows is A || B true?

  3. For int n = 7;, type the value of !(n > 5 && n < 10).

Part 5: Comparing Objects: Aliases, null, and equals

🔀 Conditionals (Advanced)

Part 5 of 7 — Comparing Objects: Aliases, null, and equals


CED Topic 2.6 also covers comparing objects. For object variables, == and != compare references: they ask whether two variables refer to the same object. To ask whether two objects hold the same data, use a method such as equals.

In this part
Aliases and reference comparison
String equality, built at run time
Comparing with null safely
Comparing objects of other classes

Aliases

Assume a class Point with a constructor Point(int x, int y) and methods getX() and getY().

Point p = new Point(2, 3);
Point q = new Point(2, 3);
Point r = p;

Two new calls create two separate objects. The assignment r = p copies the reference, so r and p refer to the same object. Two variables that refer to the same object are aliases.

ExpressionValueReason
p == qfalsetwo different objects, even with equal data
p == rtruealiases of one object
p != qtruedifferent references
p.getX() == q.getX()truecompares two int values, 2 and 2

Strings: == vs. equals

String a = "cat";
String b = new String("cat");
String c = a;
String d = "ca";
d += "t";
ExpressionValueReason
a.equals(b)truesame characters
a == bfalsenew always creates a separate object
a == ctruealiases
d.equals(a)truesame characters
d == afalse+= builds a new String object at run time

🔑 Use equals to compare String content, every time. Whether == happens to be true depends on how each String was created, which is exactly why it is unreliable.

Concept Check 🎯

Segment A

String s1 = "java";
String s2 = new String("java");
String s3 = s1;
String s4 = "ja";
s4 += "va";

Comparing with null

A reference variable that refers to no object holds null. You can compare any reference with null using == or !=, but you cannot call a method through a null reference.

String name = null;
ExpressionResult
name == nulltrue
name.equals("Ann")throws a NullPointerException
"Ann".equals(name)false, with no exception
name != null && name.equals("Ann")false; short-circuiting skips the call

Calling equals on a non-null object with a null argument simply returns false.

Comparing Objects of Other Classes

String has its own equals method that compares characters. Many classes provide an equals method that decides when two of their objects count as equivalent, and its documentation says what it compares.

If a class like Point has no such method, compare the data yourself:

boolean samePlace = p.getX() == q.getX() && p.getY() == q.getY();

Common Errors

CodeProblem
if (word == "yes")compares references; use word.equals("yes")
if (word.equals("yes")) when word might be nullcan throw; check word != null first or write "yes".equals(word)
if (p == q) to test equal coordinatestrue only for aliases

Safe Comparisons 🎯

Reference or Content? 🔍

Part 5 Summary

QuestionTool
Same object?== or != on the references
Same String content?equals
Does it refer to an object at all?== null or != null
Safe call on a possibly null Strings != null && s.equals(t), or "literal".equals(s)
Same data in a class without equalsCompare the values returned by its accessor methods

🎯 AP Connection: In a free-response answer, comparing Strings with == instead of equals is a standard deduction, even when the output happens to be right for the given test.

Part 6: AP-Style Practice

🔀 Conditionals (Advanced)

Part 6 of 7 — AP-Style Practice


This part is exam practice for CED Topics 2.4 through 2.6: multiple-choice questions on chains, nesting and equivalence, then two free-response style methods with a scoring checklist.

In this part
Multiple-choice practice
FRQ-style method 1: shippingCost
FRQ-style method 2: classify
What earns and loses points

Multiple Choice 🎯

Segment A

int x = 7;
int y = 3;
if (x > 5) {
    if (y > 5) {
        x = 0;
    } else {
        y = x + y;
    }
} else if (y < 5) {
    y = 0;
}
x = x - y;
System.out.println(x + " " + y);

FRQ-Style Method 1: shippingCost

A store charges by package weight in pounds.

WeightStandard cost
1 or less6
more than 1, up to 510
more than 5, up to 2018
more than 2018 plus 2 for each pound over 20

Express shipping adds 7 to any package. Members get free standard shipping on packages of 5 pounds or less, but still pay the 7 for express.

Write shippingCost(int pounds, boolean express, boolean member).

A Full-Credit Solution

public static int shippingCost(int pounds, boolean express, boolean member) {
    int cost;
    if (member && pounds <= 5) {
        cost = 0;
    } else if (pounds <= 1) {
        cost = 6;
    } else if (pounds <= 5) {
        cost = 10;
    } else if (pounds <= 20) {
        cost = 18;
    } else {
        cost = 18 + 2 * (pounds - 20);
    }
    if (express) {
        cost += 7;
    }
    return cost;
}
CallStandard partExpress partReturns
shippingCost(1, false, false)606
shippingCost(4, true, true)077
shippingCost(20, false, true)18018
shippingCost(25, true, false)18 + 10 = 28735

Scoring Checklist

  • The member case is tested before the weight chain, and only for 5 pounds or less.
  • The chain uses <= at 1, 5 and 20, with the smallest threshold first.
  • The over-20 formula charges only for the pounds above 20.
  • Express is a separate if, so it applies on every path.
  • The method returns the cost.

Check the Method 🎯

FRQ-Style Method 2: classify

Write classify(int a, int b, int c), which describes three side lengths:

  • "invalid" if any side is 0 or less, or if some side is at least the sum of the other two;
  • otherwise "equilateral" if all three sides are equal;
  • otherwise "isosceles" if exactly two sides are equal;
  • otherwise "scalene".

A Full-Credit Solution

public static String classify(int a, int b, int c) {
    if (a <= 0 || b <= 0 || c <= 0) {
        return "invalid";
    }
    if (a >= b + c || b >= a + c || c >= a + b) {
        return "invalid";
    }
    if (a == b && b == c) {
        return "equilateral";
    }
    if (a == b || b == c || a == c) {
        return "isosceles";
    }
    return "scalene";
}

The order of the checks does real work. Because the equilateral case returns first, the isosceles test can use || without excluding three equal sides.

CallResultDeciding test
classify(3, 4, 5)scaleneno two sides equal
classify(2, 2, 3)isoscelesa == b
classify(1, 2, 3)invalidc >= a + b, since 3 >= 3
classify(5, 5, 5)equilaterala == b && b == c
classify(0, 4, 4)invalida <= 0

Common Deductions

MistakeWrong result
a > b + c instead of >=classify(1, 2, 3) returns "scalene"
a == b == cdoes not compile
isosceles test placed before equilateralclassify(5, 5, 5) returns "isosceles"
isosceles test missing a == cclassify(3, 4, 3) returns "scalene"

Applied Recall ✍️

  1. What does shippingCost(21, false, false) return?

  2. What does shippingCost(5, false, true) return?

  3. Type the word classify(4, 4, 9) returns, without quotation marks.

Part 7: Synthesis Review

🔀 Conditionals (Advanced)

Part 7 of 7 — Synthesis Review


This review ties together the advanced conditional skills from this lesson: multiway chains, nested decisions, equivalent expressions, and object comparison.

In this part
The whole lesson in one table
A checklist for writing conditionals
Mixed review

The Lesson in One Table

PartBig ideaOne-line reminder
1Nested ifs and patternsAn unbraced else pairs with the nearest if
2else-if chainsFirst true test wins; order thresholds; test the boundaries
3NestingOne path per combination; an inner else needs the outer test true
4EquivalenceTruth tables, De Morgan, and one counterexample to disprove
5Objects== asks "same object?"; equals asks "same content?"
6PracticeSeparate adjustments from the chain; return the result

A Checklist for Writing Conditionals

  1. List the categories and their boundaries before writing code.
  2. Choose the order. For >= thresholds, go from the largest down; for <=, from the smallest up.
  3. Decide what is inside the chain. An adjustment that applies on every path, like an express fee, goes in a separate if after it.
  4. Check every boundary value, plus a case for each path through any nesting.
  5. Compare objects with equals, and guard against null first.
  6. Negate carefully. Flip each comparison, including the equal case, and swap && with ||.

Mixed Review 🎯

Segment A

int n = 15;
String s = "";
if (n % 3 == 0) {
    s += "fizz";
} else if (n % 5 == 0) {
    s += "buzz";
}
if (n % 5 == 0 && n % 3 != 0) {
    s += "!";
}
System.out.println(s);

Segment B

String cat;
if (age >= 13) {
    cat = "teen";
} else if (age >= 20) {
    cat = "adult";
} else {
    cat = "child";
}

Rules Review 🔍

Final Recall ✍️

  1. In Segment A, what is printed when n is 10?

  2. Part 2's zone method returns 1 for 50 miles or less, 2 for 51 to 300, 3 for 301 to 1000, and 4 for more than 1000. What does zone(51) return?

  3. What does classify(7, 7, 7) return? Type the word without quotation marks.

Ready for What Comes Next

If you can...You are ready for...
Order a chain and test its boundariescategory methods in free-response questions
Rewrite a condition with De Morgan's lawsloop conditions, which are often written as negations
Compare objects with equals and guard against nullsearching through lists of objects

🎯 AP Connection: Many multiple-choice items present three code segments and ask which work. Test each one with the same small set of boundary inputs, and a single failing input is enough to rule a segment out.