impera Open Impera

AP Computer Science A · Selection and iteration

if statements

1if and if-else

An if statement runs code only when a condition is true:

if (score >= 90) {
    grade = "A";
}

An if-else chooses between two paths:

if (temp > 30) {
    System.out.println("Hot");
} else {
    System.out.println("Not hot");
}

Braces { } group statements. Without braces, only the next single statement belongs to the if, a common source of bugs.

Check yourself

Without braces, how many statements does an if control?

  • One

  • Two

  • All until the next blank line

  • None

Show the answer

One

Only the next statement.

2Multi-way selection

An if-else-if chain tests conditions in order and runs only the first true branch:

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

Order matters: if the >= 70 test came first, a score of 95 would get "C".

Compare with separate if statements, where every condition is checked and several branches can run.

Worked example

score = 85.

  1. Chain above: >= 90 false, >= 80 true → "B"; stops.
  2. Three separate if statements written in the order >= 70 → "C", >= 80 → "B", >= 90 → "A": the first sets "C", the second overwrites it with "B", the third is false. The result is "B", but every condition was checked, and in a different order the final value could be wrong.

An if-else-if chain tests conditions in order and stops at the first true one

Check yourself

In an if-else-if chain, how many branches run?

  • All whose conditions are true

  • Exactly two

  • Always all of them

  • At most one

Show the answer

At most one

First true branch only.

3Nested if statements

An if inside another if:

if (age >= 16) {
    if (hasLicence) {
        System.out.println("Can drive");
    } else {
        System.out.println("Needs a licence");
    }
}

Dangling else: an else belongs to the nearest unmatched if, regardless of indentation. Braces remove the ambiguity.

Nested ifs can often be combined with &&: if (age >= 16 && hasLicence).

Check yourself

An else without braces matches:

  • The first if in the method

  • No if (compile error)

  • The if with the same indentation

  • The nearest preceding unmatched if

Show the answer

The nearest preceding unmatched if

Indentation is ignored.

4Comparing objects in conditions

  • Use equals for strings: if (answer.equals("yes")).
  • Check for null before calling methods: if (name != null && name.equals("Ada")).
  • Boolean variables can be used directly: if (done) rather than if (done == true).
Check yourself

Which condition is best style for a boolean variable found?

  • if (found.equals(false))

  • if (found == false == true)

  • if (found = false)

  • if (!found)

Show the answer

if (!found)

Use the boolean directly.

5Going deeper: chains against separate ifs, the dangling else, and tracing

Three shapes

  • One-way: if (condition) { ... } runs the block or skips it.
  • Two-way: if (...) { ... } else { ... } runs exactly one of two blocks.
  • Multi-way: if ... else if ... else if ... else runs exactly one block: the first whose condition is true (or the final else).

An else-if chain is not the same as separate ifs.

// Chain: at most one branch runs
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else {
    grade = "C";
}
// Separate ifs: every condition is tested
if (score >= 90) { grade = "A"; }
if (score >= 80) { grade = "B"; }
if (score >= 70) { grade = "C"; }

For score = 95, the chain gives "A". The separate ifs give "C": all three conditions are true, and the last assignment wins.

Order matters in a chain. Test the most restrictive condition first.

Worked example

what does this print for score = 95?

if (score >= 70) {
    System.out.println("C");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 90) {
    System.out.println("A");
}
  1. The first condition, 95 >= 70, is true.
  2. "C" is printed and the rest of the chain is skipped.
  3. The later branches can never run for any score of 70 or more: a logic error.

The dangling else: an else pairs with the nearest unmatched if, whatever the indentation suggests.

if (a > 0)
    if (b > 0)
        System.out.println("both positive");
else
    System.out.println("a is not positive");

The else belongs to if (b > 0). With a = 5 and b = −1 this prints "a is not positive", which is wrong. Braces fix it. Always use braces.

Without braces, only one statement is controlled.

if (x > 10)
    System.out.println("big");
    System.out.println("done");

"done" prints every time.

A stray semicolon ends the if. if (x > 10); has an empty body; the block that follows always runs.

Nested ifs and &&: if (a) { if (b) { S } } is the same as if (a && b) { S }, provided there are no else branches.

Worked example (trace): what is printed for x = 7, y = 3?

if (x > 5) {
    if (y > 5) {
        System.out.print("A");
    } else {
        System.out.print("B");
    }
    System.out.print("C");
} else {
    System.out.print("D");
}
System.out.print("E");
  1. x > 5 is true: enter the outer block.
  2. y > 5 is false: print "B".
  3. Then "C" (still inside the outer block).
  4. Skip the outer else; print "E".
  5. Output: BCE.

Choosing test values: to check a conditional, test each branch and the boundaries. For score >= 90, try 89, 90 and 91. Most errors are at the edges (> where >= was meant).

Returning from branches: in a method, return leaves at once, so later code acts as the "else".

public String sign(int n) {
    if (n > 0) {
        return "positive";
    }
    if (n < 0) {
        return "negative";
    }
    return "zero";
}

Every path through a non-void method must reach a return, or the code does not compile.

Comparing in conditions

  • Primitives: ==.
  • Strings and other objects: .equals.
  • Null checks: ==, and before calling any method on the reference.

Common mistakes

  • Using separate ifs where a chain is needed.
  • Putting conditions in the wrong order.
  • = in place of ==.
  • A semicolon after the condition.
  • Omitting braces and assuming indentation groups statements.
  • Missing a return on one path.
Check yourself

For x = 4, what does if (x > 2) { x += 3; } if (x > 5) { x *= 2; } leave in x?

  • 4

  • 8

  • 7

  • 14

Show the answer

14

Both ifs are tested: x becomes 7, then 14.

6For top marks

  • Put the most restrictive condition first in a chain of ranges (e.g. >= 90 before >= 80).
  • Always use braces in free-response answers.
  • Check boundary values: does a score of exactly 80 get the right grade?
  • Do not use = inside a condition when you mean ==.
Example

a method returning the larger of two ints: if (a > b) return a; else return b; (or return Math.max(a, b);).

Check yourself

A ticket costs $5 for under 12 and $8 otherwise. Which code is correct?

  • if (age < 12) price = 8; else price = 5;

  • if (age < 12) price = 5; else price = 8;

  • if (age <= 12) price = 5; price = 8;

  • if (age > 12) price = 5; else price = 8;

Show the answer

if (age < 12) price = 5; else price = 8;

Under 12 → 5.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera