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:
| Original | Equivalent | Why |
|---|---|---|
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 100 | Common 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 ✍️
-
In a dangling else situation, the else always pairs with the _______ unmatched if.
-
The statement if (flag == true) can be simplified to if (_______).
-
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, butMath.max()andMath.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 requiresx > 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.
weight | First true test | cost |
|---|---|---|
| 8 | weight <= 8 | 5 |
| 9 | weight <= 32 | 9 |
| 32 | weight <= 32 | 9 |
| 100 | weight <= 160 | 15 |
| 161 | none, so the else runs | 25 |
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 test | Correct order |
|---|---|
>= or > thresholds | Largest threshold first |
<= or < thresholds | Smallest 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";
}
temp | Should be | This code gives | Problem |
|---|---|---|---|
| 59 | cold | cold | |
| 60 | mild | hot | temp > 60 leaves a gap at 60 |
| 80 | mild | hot | temp < 80 leaves a gap at 80 |
| 81 | hot | hot |
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 less | 1 |
| 51 to 300 | 2 |
| 301 to 1000 | 3 |
| more than 1000 | 4 |
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:
miles | 50 | 51 | 300 | 301 | 1000 | 1001 |
|---|---|---|---|---|---|---|
| Zone | 1 | 2 | 2 | 3 | 3 | 4 |
🎯 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 ✍️
-
What does
zone(300)return? -
What does
zone(1001)return? -
In the shipping chain, what is
costwhenweightis 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:
member | total | Path | discount |
|---|---|---|---|
| true | 60 | member, at least 50 | 10 |
| true | 30 | member, under 50 | 5 |
| false | 120 | non-member, at least 100 | 5 |
| false | 80 | non-member, under 100 | 0 |
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, c | Path | big |
|---|---|---|
| 3, 7, 5 | a >= b false; b >= c true | 7 |
| 9, 2, 9 | a >= b true; a >= c true | 9 |
| 4, 4, 6 | a >= b true; a >= c false | 6 |
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 ✍️
-
In the discount code, what is
discountwhenmemberis true andtotalis 50? -
In the discount code, what is
discountwhenmemberis false andtotalis 99? -
Version 1 of largest of three runs with
a = 2,b = 2,c = 1. What isbig?
Part 3 Summary
| Idea | Rule |
|---|---|
| Nested ifs | One path per combination of answers; test an input for each path |
| No else anywhere | if (a) { if (b) ... } is if (a && b) |
| Inner else | Runs only when the outer test is true and the inner one is false |
| Outer else | Close the inner if with a brace before the else |
| Largest of three | Nested >= tests, or a running largest with separate ifs |
Strict > on ties | Two 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.
A | B | A && B | A || B | !A |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
Proving De Morgan's Law
A | B | !(A && B) | !A || !B | !A && !B |
|---|---|---|---|---|
| true | true | false | false | false |
| true | false | true | true | false |
| false | true | true | true | false |
| false | false | true | true | true |
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
A | B | C | A && (B || C) | (A && B) || (A && C) | A || (B && C) | (A || B) && C |
|---|---|---|---|---|---|---|
| T | T | T | T | T | T | T |
| T | T | F | T | T | T | F |
| T | F | T | T | T | T | T |
| T | F | F | F | F | T | F |
| F | T | T | F | F | T | T |
| F | T | F | F | F | F | F |
| F | F | T | F | F | F | F |
| F | F | F | F | F | F | F |
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
| Expression | Its negation |
|---|---|
x < y | x >= y |
x <= y | x > y |
x > y | x <= y |
x >= y | x < y |
x == y | x != y |
x != y | x == 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 ||:
| Original | Step | Result |
|---|---|---|
!(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
| Expression | Value for every input | Name |
|---|---|---|
x > 5 || x <= 5 | always true | tautology |
x > 5 && x <= 5 | always false | contradiction |
A || (A && B) | same as A | the && B part never changes the result |
!(!A) | same as A | double negation |
Negate and Simplify 🔍
Apply De Morgan 🎯
Applied Recall ✍️
-
Type the value of
!(true && !false). -
In a two-variable truth table, in how many rows is
A || Btrue? -
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.
| Expression | Value | Reason |
|---|---|---|
p == q | false | two different objects, even with equal data |
p == r | true | aliases of one object |
p != q | true | different references |
p.getX() == q.getX() | true | compares 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";
| Expression | Value | Reason |
|---|---|---|
a.equals(b) | true | same characters |
a == b | false | new always creates a separate object |
a == c | true | aliases |
d.equals(a) | true | same characters |
d == a | false | += builds a new String object at run time |
🔑 Use
equalsto 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;
| Expression | Result |
|---|---|
name == null | true |
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
| Code | Problem |
|---|---|
if (word == "yes") | compares references; use word.equals("yes") |
if (word.equals("yes")) when word might be null | can throw; check word != null first or write "yes".equals(word) |
if (p == q) to test equal coordinates | true only for aliases |
Safe Comparisons 🎯
Reference or Content? 🔍
Part 5 Summary
| Question | Tool |
|---|---|
| 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 String | s != null && s.equals(t), or "literal".equals(s) |
Same data in a class without equals | Compare the values returned by its accessor methods |
🎯 AP Connection: In a free-response answer, comparing Strings with
==instead ofequalsis 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.
| Weight | Standard cost |
|---|---|
| 1 or less | 6 |
| more than 1, up to 5 | 10 |
| more than 5, up to 20 | 18 |
| more than 20 | 18 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;
}
| Call | Standard part | Express part | Returns |
|---|---|---|---|
shippingCost(1, false, false) | 6 | 0 | 6 |
shippingCost(4, true, true) | 0 | 7 | 7 |
shippingCost(20, false, true) | 18 | 0 | 18 |
shippingCost(25, true, false) | 18 + 10 = 28 | 7 | 35 |
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.
| Call | Result | Deciding test |
|---|---|---|
classify(3, 4, 5) | scalene | no two sides equal |
classify(2, 2, 3) | isosceles | a == b |
classify(1, 2, 3) | invalid | c >= a + b, since 3 >= 3 |
classify(5, 5, 5) | equilateral | a == b && b == c |
classify(0, 4, 4) | invalid | a <= 0 |
Common Deductions
| Mistake | Wrong result |
|---|---|
a > b + c instead of >= | classify(1, 2, 3) returns "scalene" |
a == b == c | does not compile |
| isosceles test placed before equilateral | classify(5, 5, 5) returns "isosceles" |
isosceles test missing a == c | classify(3, 4, 3) returns "scalene" |
Applied Recall ✍️
-
What does
shippingCost(21, false, false)return? -
What does
shippingCost(5, false, true)return? -
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
| Part | Big idea | One-line reminder |
|---|---|---|
| 1 | Nested ifs and patterns | An unbraced else pairs with the nearest if |
| 2 | else-if chains | First true test wins; order thresholds; test the boundaries |
| 3 | Nesting | One path per combination; an inner else needs the outer test true |
| 4 | Equivalence | Truth tables, De Morgan, and one counterexample to disprove |
| 5 | Objects | == asks "same object?"; equals asks "same content?" |
| 6 | Practice | Separate adjustments from the chain; return the result |
A Checklist for Writing Conditionals
- List the categories and their boundaries before writing code.
- Choose the order. For
>=thresholds, go from the largest down; for<=, from the smallest up. - Decide what is inside the chain. An adjustment that applies on every path, like an express fee, goes in a separate if after it.
- Check every boundary value, plus a case for each path through any nesting.
- Compare objects with
equals, and guard againstnullfirst. - 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 ✍️
-
In Segment A, what is printed when
nis 10? -
Part 2's
zonemethod returns 1 for 50 miles or less, 2 for 51 to 300, 3 for 301 to 1000, and 4 for more than 1000. What doeszone(51)return? -
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 boundaries | category methods in free-response questions |
| Rewrite a condition with De Morgan's laws | loop conditions, which are often written as negations |
Compare objects with equals and guard against null | searching 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.