AP Computer Science A · Unit 2 lecture · Part 12 of 12 · 10 min

Unit 2 wrap-upPut it together

Mr. Thompkins
You've got the whole unit: decisions, logic and loops. Let's tie it together. Every question in this unit comes down to two habits: evaluate each test with the values the variables hold right then, and trace loops one pass at a time.
TopicThe one thing to remember
Boolean expressions (2.2)Relational operators give true or false; == on doubles is risky
if, else, else if (2.3-2.4)Separate ifs are all checked; a chain runs only its first true branch
&&, ||, ! (2.5)Short-circuit: the right side may never run
Equivalence (2.6)De Morgan flips the operator; equals for contents, == for same object
while, for (2.7-2.8)Check before every pass; count passes from the bounds
Algorithms (2.9-2.10)Sum, count, max/min, any/all, digits, String traversal
Nested loops (2.11-2.12)The inner loop runs fully for each outer pass; multiply or add up
Unit 2 on one page.
?Wait, when do I use a for loop and when a while loop?
Use a for loop when you know how many passes you need, or you're counting through a range or a String. Use a while loop when you repeat until something happens and don't know how many passes it will take, like stripping digits or waiting for a value to cross a line. Either can always be rewritten as the other.

Three threads run through this unit. First, Boolean expressions drive everything: every if, every while and every for has a test, and short-circuiting and De Morgan's laws are about those tests. Second, order matters: the first true branch of a chain wins, the condition of a loop is checked before every pass, and the inner loop finishes before the outer loop moves on. Third, patterns repeat: count, sum, max, any or all, digits, and String traversal show up again in Unit 4 with arrays and ArrayLists.

Pause and think
Connect two topics: why is s.length() > 0 && s.substring(0, 1).equals("Q") a safe test, while the same loop over s with i <= s.length() is not?
I thought about it. Show me
In the test, short-circuiting skips substring whenever the String is empty, so it never asks for a character that isn't there. In the loop, nothing guards the last pass: when i equals s.length(), substring(i, i + 1) asks for an index past the end and throws a StringIndexOutOfBoundsException.

Traps that cost points

✕ Treating separate if statements like an else-if chain.
✓ Separate ifs are all checked, each with the current values. A chain runs only its first true branch.
✕ Ordering a chain from broad to specific.
✓ A broad test first swallows everything. Put the strictest test first.
✕ Writing 1 <= x <= 10.
✓ Use two comparisons: x >= 1 && x <= 10.
✕ !(a && b) becomes !a && !b.
✓ De Morgan flips the operator: !a || !b.
✕ Putting the risky part on the left of &&.
✓ Guard first: s.length() > 0 && s.substring(0, 1)...
✕ Comparing Strings with ==.
✓ == asks "same object?". Use equals for the characters.
✕ Off-by-one bounds: < versus <=, length() versus length() - 1.
✓ Check the first and last values the loop variable takes.
✕ Stopping a trace one pass early.
✓ Check the condition after every update. The loop ends only when the check is false.
✕ Starting a max at 0.
✓ Start at the first value or Integer.MIN_VALUE.
✕ return false in an else inside an "any" loop.
✓ Return false only after the loop has checked everything.
✕ Multiplying bounds when the inner loop depends on the outer one.
✓ Add up the inner passes for each outer value.

Unit 2 syntax sheet

== != < > <= >=
Relational operatorsProduce a boolean; use equals for Strings
a && b a || b !a
And, or, notPrecedence: !, then &&, then ||
!(a && b) is !a || !b
De MorganAnd !(a || b) is !a && !b
if (...) { } else if (...) { } else { }
Multiway selectionOnly the first true branch runs
while (cond) { ... }
Repeat while trueChecked before every pass; may run 0 times
for (int i = a; i < b; i++)
Counting loopRuns b - a times; with <=, b - a + 1
n % d == 0
d divides nn % 2 == 0 for even
n % 10 n /= 10
Last digit; drop the last digitLoop while n > 0
s.substring(i, i + 1)
The character at index iLoop with i < s.length()
n(n + 1) / 2
1 + 2 + ... + nCounting passes of a dependent nested loop

FRQ strategy for Unit 2

  1. Unit 2 is the control-structure half of Question 1, Methods and Control Structures (7 points): part A usually needs a loop with an if inside, and part B a String traversal. Loops and ifs also appear in every other FRQ.
  2. Name the pattern before you write: count, sum, max or min, any or all, digits, or build a String. Then write its three parts: set up, loop, use the result.
  3. Write the loop header from the first and last values you need. Test it on the shortest input the preconditions allow, including an empty String or a one-digit number.
  4. Put return inside the loop only for an early answer (found it, or it failed). Put the default return after the loop.
  5. Compare Strings with equals. Get single characters with substring(i, i + 1).
  6. Don't print when the method should return. Don't change a parameter you'll need later; copy it into a local variable first.
Mixed FRQ practice
Write a static method removeVowels(String s) that returns a new String with every lowercase vowel (a, e, i, o, u) removed. removeVowels("education") returns "dctn", and removeVowels("rhythm") returns "rhythm". Precondition: s contains only lowercase letters.
  1. Pattern: build a String. Before the loop: String result = "";.
    Why?
    Strings are immutable, so you can't delete letters from s. You build a new String out of the letters you keep.
  2. Visit every index: for (int i = 0; i < s.length(); i++), with String ch = s.substring(i, i + 1); inside.
  3. Keep ch only if it isn't a vowel. One test does it: "aeiou".indexOf(ch) == -1 is true exactly when ch is not one of the five vowels. Then result += ch;.
    Why?
    You could also write five equals tests joined by ||, wrapped in !( ). indexOf is shorter and harder to get wrong.
  4. After the loop, return result;. Check "education": e, u, a, i, o are dropped, leaving d, c, t, n: "dctn".

Answer:

public static String removeVowels(String s)
{
    String result = "";
    for (int i = 0; i < s.length(); i++)
    {
        String ch = s.substring(i, i + 1);
        if ("aeiou".indexOf(ch) == -1)
        {
            result += ch;
        }
    }
    return result;
}

removeVowels("education") returns "dctn" and removeVowels("rhythm") returns "rhythm" (checked under Java 17).

Stuck? Get a hint
  1. Which pattern builds a new String? Start from "".
  2. Get each character with substring(i, i + 1).
  3. "aeiou".indexOf(ch) is -1 when ch is not a vowel. Keep those.
Check yourself
What is printed?
int n = 30405;
int count = 0;
while (n > 0)
{
    int d = n % 10;
    if (d % 2 == 0)
    {
        count++;
    }
    n /= 10;
}
System.out.println(count);
  1. A4
  2. B3
  3. C5
  4. D2
Show the answer

B. The loop looks at each digit of 30405 from the right: 5, 0, 4, 0, 3. The test d % 2 == 0 counts the even digits, 0, 4 and 0, so it prints 3. Choice C counts every digit, and choice D forgets that 0 is even.

Check yourself
Which condition is true exactly when the int x is NOT between 1 and 100, inclusive?
  1. Ax < 1 && x > 100
  2. B!(x >= 1 || x <= 100)
  3. Cx < 1 || x > 100
  4. Dx <= 1 || x >= 100
Show the answer

C. "Between 1 and 100, inclusive" is x >= 1 && x <= 100. By De Morgan, its negation is x < 1 || x > 100. Choice A can never be true: no x is both below 1 and above 100. Choice B negates the wrong expression (it uses ||), and choice D wrongly excludes 1 and 100.

Mr. Thompkins
That's Unit 2, the biggest unit on the exam, done. Take the Unit 2 quiz now, and trace every loop question with a table, even the easy ones. When you miss one, come back to its section and redo the walk. See you in Unit 3, where you start writing your own classes.