AP Computer Science A · Unit 2: Selection & Iteration
2.2 If Statements and Control Flow
Basic if statement
An if statement lets a program execute code only when a boolean expression evaluates to true. Syntax: `if (condition) { statement(s); }`. If the condition is false, the block is skipped entirely and control flow moves to the code after the if statement.
if-else and control flow
An if-else statement provides an alternative path: if the condition is true, the if-block runs; otherwise, the else-block runs. Only one branch ever executes. This creates a fork in the program's control flow, meaning statements execute conditionally instead of strictly top to bottom.
Nested and chained conditionals
You can nest if statements inside other if/else blocks to test multiple conditions, or chain them using else if to check several mutually exclusive options in order. Only the first true condition's block executes; the rest are skipped, even if they'd also be true.
Key terms
- if statement
- A control structure that executes a block of code only if its boolean condition is true.
- if-else statement
- Executes the if-block when the condition is true, otherwise executes the else-block; only one runs.
- else if chain
- A sequence of conditions checked in order; only the first true condition's block executes.
- Nested if statement
- An if statement placed inside another if or else block, used to test additional conditions.
- Control flow
- The order in which statements execute; conditionals like if/else create branching paths instead of strict top-to-bottom execution.
Try an AP-style question
Code
int x = 10;
if (x > 5)
x = x * 2;
x = x + 1;What is x?
- 20
- 10
- 11
- 21
Show the answer
D. 10 → 20 → 21.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 2.2 free in APrep