AP Computer Science A · Topic 3.2
if Statements and Control Flow Practice
Part of Boolean Expressions and if Statements.
Practice questions
12
Sample questions
5 of 12 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 1/5
Which is valid Java syntax for an if-statement?
- A
if x > 0: { ... }
- Bcheck_circle
if (x > 0) { ... }
- C
if (x > 0) then { ... }
- D
if x > 0 { ... }
Why
Java requires parentheses around the condition.
- A
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;
- Ccheck_circle
int y = x > 0 ? 1 : -1;
- 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.
- A
Sample 3difficulty 2/5
if (x > 0) x--; y++;Why is this misleading?
- A
Both statements depend on the if
- B
x-- never executes
- Ccheck_circle
Only x-- depends on the if; y++ always runs
- 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.
- A
Sample 4difficulty 2/5
For <code>boolean done = true;</code>, which is correct?
- A
Neither works
- B
if (done == true) ...
- Ccheck_circle
Both work; second is preferred (idiomatic)
- D
if (done) ...
Why
Both compile; idiomatic Java prefers <code>if (done)</code> over <code>if (done == true)</code>.
- A
Sample 5difficulty 2/5
<code>if (x > 0); System.out.println("hello");</code> always prints "hello" because
- A
if-statement is ignored
- Bcheck_circle
Trailing semicolon makes the if-body empty; the print runs unconditionally
- C
x > 0 always true
- D
Compile error
Why
The semicolon ends the if; print is no longer part of the if.
- A