Mastering Control Flow in Java

Boolean Expressions and Logic

At the heart of selection (making decisions) and iteration (repeating tasks) lies the Boolean expression. These are statements that evaluate to either true or false.

Relational Operators

Relational operators compare two values. In the AP Java subset, these are applied strictly to primitive numbers (int, double), and the result is always a boolean.

OperatorMeaningExample (x = 5, y = 10)Result
==Equal tox == yfalse
!=Not equal tox != ytrue
<Less thanx < ytrue
<=Less than or equal tox <= 5true
>Greater thany > xtrue
>=Greater than or equal toy >= 20false

Logical Operators

To combine multiple boolean conditions, we use logical operators. The order of operations is crucial: NOT (!) has the highest precedence, followed by AND (&&), and finally OR (||).

Visual Truth Table for AND, OR, and NOT operators

  1. NOT (!): Inverts the boolean value.
    • !true $\rightarrow$ false
  2. AND (&&): True only if both operands are true.
  3. OR (||): True if at least one operand is true.
Short-Circuit Evaluation

Java uses short-circuit evaluation for efficiency and error prevention.

  • AND (&&): If the left operand is false, the result is automatically false. Java does not evaluate the right side.
  • OR (||): If the left operand is true, the result is automatically true. Java does not evaluate the right side.

Application: This is often used to prevent arithmetic errors, such as division by zero:

int count = 0;
int total = 100;

// If count is 0, the first part is false.
// The division (total / count) is NEVER executed, preventing a crash.
if (count != 0 && total / count > 5) {
    System.out.println("Average is greater than 5");
}

De Morgan’s Laws

One of the most frequently tested concepts on the AP exam involves simplifying negated complex boolean expressions. You must know how to distribute the NOT operator.

The Rules:

  1. !(A && B) is equivalent to !A || !B
  2. !(A || B) is equivalent to !A && !B

Study Tip/Mnemonic: "Break the bar, change the sign." (If you draw a bar over the expression to represent NOT, break it over the operators and flip the AND to OR).

Example:

  • Determine if a number x is not inside the range [10, 20].
  • Logic: ! (x >= 10 && x <= 20)
  • Applied De Morgan's: x < 10 || x > 20

Selection Statements (Conditionals)

Selection allows a program to execute code segments conditionally. This dictates the "flow" of the program.

The if and if-else Statements

The single-way selection (if) executes code only if the condition is true. Two-way selection (if-else) provides an alternative path.

Flowchart demonstrating if-else-if logic flow

int score = 85;

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B"); // This executes
} else {
    System.out.println("C or lower");
}

Block Scope and Braces

While Java allows you to omit curly braces {} if the block contains only one line of code, always use braces on the AP exam (and in real life). This prevents the "dangling else" error where an else accidentally attaches to the wrong if.

Comparing Objects vs. Primitives

This is a critical distinction in Unit 2 logic.

  • Primitives (int, double): Use == to compare values.
  • Objects (specifically String): == compares memory citations (references), not content. You must use the .equals() method.

Diagram showing stack and heap memory distinction for String comparison

The Pitfall:

String s1 = new String("Hello");
String s2 = new String("Hello");

if (s1 == s2) { ... }       // FALSE (Different memory addresses)
if (s1.equals(s2)) { ... }  // TRUE (Same logic inside the object)

Iteration (Loops)

Iteration allows code to repeat. The AP Java subset focuses on while loops, for loops, and enhanced for-each loops (typically covered with Arrays). We will focus on the standard while and for here.

The while Loop

A while loop is used when the number of iterations is not known in advance. It continues as long as the boolean condition remains true.

Syntax:

while (boolean expression) {
    // statements
}

Key Characteristics:

  • It is a pre-test loop (the condition is checked before the loop runs).
  • If the condition is initially false, the loop body executes zero times.
  • You are responsible for manually updating the variable to avoid an infinite loop.

Example: Digit extraction algorithm
(Very common on AP FRQs)

int n = 729;
while (n > 0) {
    int digit = n % 10; // Get the last digit (9, then 2, then 7)
    System.out.print(digit);
    n /= 10;            // Remove the last digit (72, then 7, then 0)
}
// Output: 927

The for Loop

The for loop is concise and typically used for definite iteration (when you know how many times you want to loop).

Syntax:

for (initialization; condition; update) {
    // statements
}

Execution Order:

  1. Initialization (Runs once at the start).
  2. Condition Check (If false, loop ends instantly).
  3. Body execution.
  4. Update (Increment/Decrement).
  5. Repeat step 2.

Example:

// Print even numbers from 0 to 10
for (int i = 0; i <= 10; i += 2) {
    System.out.print(i + " ");
}

Nested Loops

A loop inside another loop. For every one iteration of the outer loop, the inner loop runs to completion.

Complexity Note: Nested loops often imply $O(n^2)$ complexity. If the outer loop runs $n$ times and the inner loop runs $n$ times, the body executes $n \times n$ times.

Example: Printing a Triangle pattern

for (int r = 1; r <= 5; r++) {
    for (int c = 1; c <= r; c++) {
        System.out.print("*");
    }
    System.out.println();
}
/* Output:
*
**
***
****
*****
*/

Mathematical Analysis of Loops

On the AP exam, you will often find multiple-choice questions asking "How many times does this loop execute?"

Standard Range Formula

For a loop: for (int i = A; i < B; i++)

  • Number of iterations = $B - A$

For a loop: for (int i = A; i <= B; i++)

  • Number of iterations = $(B - A) + 1$

Tracing Tables

When facing complex loops involving changing variables, do not do it in your head. Draw a trace table.

IterationVariable iVariable kCondition i < 4?Output
Init05true-
117true7
229true9
3311true11
4413false (stop)-

Common Mistakes & Pitfalls

  1. Confusing = and ==

    • Wrong: if (x = 5) (This is an assignment, and in Java, it usually causes a compile error unless x is boolean).
    • Right: if (x == 5).
  2. String Comparisons

    • Never use if (string1 == "A"). Always use if (string1.equals("A")).
  3. The Semicolon of Death

    • Mistake: for (int i=0; i<5; i++);
    • Result: The semicolon immediate terminates the loop statement. The block following it runs only once after the loop is finished counting. The code inside the loop technically does nothing.
  4. Off-by-One Errors (OBOE)

    • Confusing < with <= usually results in a loop running one time too many or too few. Always check your boundary conditions (the first and the last value).
  5. Infinite Loops

    • Forgetting to increment the counter in a while loop, or decrementing instead of incrementing causes the condition to remain true forever. Example: for(int i=0; i>0; i++) (Wait, this one never runs!) vs for(int i=0; i>=0; i++) (This runs forever).
  6. Arithmetic Exception in Short-Circuiting

    • Checking if (x / y > 5 && y != 0) is wrong. If y is 0, the division happens before the check.
    • Flip it: if (y != 0 && x / y > 5) guarantees safety.