AP® Computer Science A · Unit 2 · Topic 2.3
The if Statement and Its Block
An if statement lets a program test a boolean condition and run a block of code only when that condition is true, skipping it entirely when false.
Every program sometimes needs to say 'do this, but only if...'. Without that ability, every line would run every time, in order, no matter what. The if statement gives you a branch point: it checks a boolean condition, and based on the result, control either enters the block that follows or jumps clean over it to whatever comes after.
Mechanically, the if evaluates the condition in parentheses. If it's true, the program executes the block — everything inside the braces — then continues with the code after that block. If it's false, the program skips the entire block and picks up right after it, as if those lines didn't exist for this run. Nothing inside the block runs partially; it's all or nothing.
The tricky part is scope: what exactly counts as 'the block'. With braces, everything between { and } is controlled. Without braces, Java only attaches the single next statement to the if — indentation is just a visual habit, not a rule the compiler follows. This matters a lot once you start writing if-else chains and nested conditionals in the rest of the unit, where misjudging what's actually inside a branch is the easiest way to write code that compiles but does the wrong thing.
Key terms
- Condition
- A boolean expression in parentheses that the if evaluates to decide whether to run its statement.
- Block
- One or more statements grouped inside braces so they are treated as a single unit.
- Controlled statement
- The single statement, or block, that an if actually governs based on its condition.
- Empty statement
- A lone semicolon that counts as a complete, do-nothing statement in Java.
Watch it explained
- How it worksHow does an if statement route control around a whole block when its test is false?
- Worked exampleTrace which lines run for x = 10 and for x = 3 in an if that tests x greater than 5.
- Common mistakeWhy doesn't an if without braces control more than the single next statement?
- Going furtherWhat happens when a stray semicolon lands right after the closing parenthesis of an if?
Check yourself
End of topic.