APrep Open the app

AP Computer Science A · Unit 2: Selection & Iteration

2.3 If-Else Statements

Adding an else branch

An if-else statement lets a program pick between two blocks of code: one runs if the condition is true, the other if it's false. Only one branch ever executes. Syntax: `if (condition) { ... } else { ... }`. This guarantees some code always runs, unlike a plain if.

Chaining with else if

Use else if to test multiple conditions in order. Java evaluates them top to bottom and executes the first true branch, skipping the rest — even if later conditions are also true. An optional final else catches all remaining cases. Order matters when conditions overlap.

Nested if statements

An if or else block can contain another if-else inside it — called nesting. This lets you test additional conditions only after an outer condition is met, creating more specific logic paths. Careful indentation and braces `{}` help avoid confusion about which else belongs to which if.

Key terms

if-else statement
A control structure that runs one block of code if a condition is true, and a different block if it's false.
else if
Allows chaining multiple conditions; Java checks them in order and runs the first true block only.
Nested if
An if-else statement placed inside another if or else block, enabling more specific conditional logic.
Why use braces {} in conditionals?
To clearly define which statements belong to which if/else, preventing logic errors when multiple statements are involved.
Mutual exclusivity in if-else chains
Only one branch in an if/else-if/else chain executes, even if multiple conditions would be true — the first true one wins.

Try an AP-style question

Code

int x = 4;
if (x > 5)
    System.out.print("A");
else
    System.out.print("B");
System.out.print("C");

What is printed?

  1. C
  2. ABC
  3. BC
  4. AC
Show the answer

C. else branch, then C.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 2.3 free in APrep