AP Computer Science A · Topic 3.2

if Statements and Control Flow Practice

Part of Boolean Expressions and if Statements.

Practice questions

12

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 12 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 1/5

    Which is valid Java syntax for an if-statement?

    • A

      if x > 0: { ... }

    • B

      if (x > 0) { ... }

      check_circle
    • C

      if (x > 0) then { ... }

    • D

      if x > 0 { ... }

    Why

    Java requires parentheses around the condition.

  2. Sample 2difficulty 2/5

    int y;
    if (x > 0) y = 1;
    else y = -1;

    Which single statement is equivalent?

    • A

      int y = x > 0 ? -1 : 1;

    • B

      int y = x ? 1 : -1;

    • C

      int y = x > 0 ? 1 : -1;

      check_circle
    • D

      int y = (x > 0) - 1;

    Why

    The ternary cond ? a : b returns a when true, b when false: y becomes 1 if x > 0, otherwise -1.

  3. Sample 3difficulty 2/5

    if (x > 0)
        x--;
        y++;

    Why is this misleading?

    • A

      Both statements depend on the if

    • B

      x-- never executes

    • C

      Only x-- depends on the if; y++ always runs

      check_circle
    • D

      Compile error due to missing braces

    Why

    Without braces, only the next single statement is part of the if. Indentation is ignored, so y++ runs unconditionally.

  4. Sample 4difficulty 2/5

    For <code>boolean done = true;</code>, which is correct?

    • A

      Neither works

    • B

      if (done == true) ...

    • C

      Both work; second is preferred (idiomatic)

      check_circle
    • D

      if (done) ...

    Why

    Both compile; idiomatic Java prefers <code>if (done)</code> over <code>if (done == true)</code>.

  5. Sample 5difficulty 2/5

    <code>if (x > 0); System.out.println("hello");</code> always prints "hello" because

    • A

      if-statement is ignored

    • B

      Trailing semicolon makes the if-body empty; the print runs unconditionally

      check_circle
    • C

      x > 0 always true

    • D

      Compile error

    Why

    The semicolon ends the if; print is no longer part of the if.