AP COMPUTER SCIENCE A • SELECTION AND ITERATION

if Statements

Control your program's decision-making by executing code only when specific Boolean conditions are met.

Historical Context & Motivation

Every useful program must make decisions. Without the ability to branch execution based on runtime data, software would be limited to a rigid, linear sequence of instructions—no logins, no game logic, no responsive user interfaces. The conditional statement was one of the earliest abstractions invented to solve this problem, allowing a machine to evaluate a condition and choose between alternative paths of execution. In Java, the primary mechanism for single-branch and multi-branch decision-making is the if statement, a construct whose ancestry stretches back to the dawn of computing.

1843
Ada Lovelace's Notes
In her notes on Babbage's Analytical Engine, Ada Lovelace described how the machine could test conditions and branch to different instruction cards—arguably the first written description of conditional logic in computing.
1957
FORTRAN IF Statement
IBM's FORTRAN introduced the arithmetic IF, which branched to one of three labels based on whether an expression was negative, zero, or positive—an early high-level conditional.
1972
C Language Structured if
Dennis Ritchie's C language formalized the if-else syntax with curly-brace blocks, establishing the pattern Java and many modern languages still follow.
1995
Java 1.0 Released
Java adopted C-style if/else syntax virtually unchanged but enforced that the condition must evaluate to a boolean—eliminating the error-prone integer-as-truth convention from C.

The central question the if statement answers is deceptively simple: given a Boolean expression, how does a program choose which block of code to execute? Mastering this construct is essential because nearly every AP Computer Science A free-response question requires conditional logic, and roughly 20% of the multiple-choice exam tests selection concepts directly.

Core Principles & Definitions

Java's selection statements come in three flavors tested on the AP exam: the one-way if, the two-way if-else, and the multi-way if-else if-else chain. Each form evaluates a Boolean expression (an expression that resolves to true or false) and uses the result to decide which block executes.

1

Boolean Guard

The parenthesized condition after if must be a boolean expression. Java does not allow integers or objects in this position—unlike C or Python.
2

Block Scope

Curly braces define the scope of the conditional body. Variables declared inside are invisible outside. Always use braces, even for single-statement bodies, to avoid dangling-else bugs.
3

Short-Circuit Evaluation

Java's && and || operators short-circuit: if the left operand of && is false, the right is never evaluated. This matters when the right operand has side effects or could throw an exception.
4

Mutually Exclusive Branches

In an if-else chain, exactly one branch executes. The JVM tests conditions top-to-bottom and enters the first branch whose condition is true, then skips the rest.
KEY TAKEAWAY
KEY TAKEAWAY

Visual Explanation — Control Flow Diagram

The diamond represents the Boolean condition. When true, control flows left into the if-body (green). When false, control flows right into the else-body (red). Both paths rejoin before the code after the if statement.

Notice that the diamond shape is the universal flowchart symbol for a decision point. In a one-way if (without an else), the false branch would bypass the if-body entirely and jump directly to the convergence point. In a multi-way if-else if chain, the false branch leads to another diamond rather than a body, creating a cascade of decisions evaluated in order.

How if Statements Work — Syntax & Semantics

One-Way if

ONE-WAY IF SYNTAX
if (condition) { statements; }
condition — any expression of type boolean; statements — zero or more Java statements executed only when condition is true.

Two-Way if-else

TWO-WAY IF-ELSE SYNTAX
if (condition) { statementsA; } else { statementsB; }
Exactly one block executes: statementsA when condition is true, statementsB otherwise.

Multi-Way if-else if-else

MULTI-WAY SYNTAX
if (c1) { ... } else if (c2) { ... } else { ... }
Conditions c1, c2, … are tested in order. The first true condition's block executes; all remaining branches are skipped. The trailing else is optional and acts as a catch-all.
Common Pitfall: = vs. ==

The AP exam frequently tests whether students understand that an if-else if chain is not the same as a sequence of independent if statements. Independent if statements allow multiple bodies to execute if multiple conditions are true, whereas an if-else if chain guarantees at most one body executes. This distinction is a perennial source of exam errors.

Common if-Statement Patterns

Certain if-statement structures appear so frequently in AP Computer Science A that recognizing them on sight will accelerate both your problem-solving and your code-tracing accuracy. The diagram below illustrates three canonical patterns side by side: independent ifs, an if-else if chain, and nested ifs.

Left: independent ifs — all conditions tested regardless. Center: an if-else if chain — at most one branch fires. Right: nested ifs — inner condition is guarded by the outer.
Comparison of conditional patterns
PatternBodies That Can ExecuteTypical Use Case
Independent ifs0 to N (any combination)Checking multiple non-exclusive flags
if-else if-elseExactly 1Grade brackets, menu routing
Nested ifs0 or 1 (inner body)Two-stage validation (bounds + business rule)

Worked Example — Letter Grade Calculator

Consider the classic AP exam scenario: given an integer variable score representing a student's percentage, assign the correct letter grade to a String variable grade using the scale A ≥ 90, B ≥ 80, C ≥ 70, D ≥ 60, and F otherwise.

1
Step 1 — Identify the StructureBecause the grade categories are mutually exclusive (a score belongs to exactly one bracket), we need an if-else if-else chain rather than independent ifs. We order conditions from highest to lowest to leverage the mutual exclusivity.
2
Step 2 — Write the CodeString grade; if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else if (score >= 60) { grade = "D"; } else { grade = "F"; }
3
Step 3 — Trace with score = 85Condition 1: 85 >= 90 → false. Condition 2: 85 >= 80 → true. The body of the second branch executes, assigning grade = "B". All remaining branches are skipped.
grade = "B"
4
Step 4 — Why Order MattersBecause we use else-if, once score >= 80 is true we know score < 90 (or the first branch would have fired). This means we do not need to write score >= 80 && score < 90—the chain structure already guarantees the upper bound. This is a key exam concept.
5
Step 5 — Edge Case: score = 90Condition 1: 90 >= 90 → true. The first body executes, assigning "A". The boundary value is handled correctly by the >= operator.
grade = "A"

Common Mistakes & Best Practices

Top 5 if-statement pitfalls on the AP exam
PitfallWhat Goes WrongBest Practice
Missing bracesOnly the first statement after if is conditional; the rest always execute.Always use { } even for single-line bodies.
Using == on Strings== compares references, not content. Two Strings with the same text may be different objects.str.equals("hello")
Independent ifs instead of else-ifMultiple bodies execute; grade example could assign A then overwrite with B.Use else-if for mutually exclusive categories.
Dangling elseAn else binds to the nearest preceding if, not the one you intended.Use braces to make nesting explicit.
Redundant conditionsWriting score >= 80 && score < 90 inside an else-if is correct but unnecessarily verbose.Trust the chain: prior false branches already limit the range.
KEY TAKEAWAY
KEY TAKEAWAY

Connection to Advanced Constructs

The if statement is the gateway to the broader category of selection in Java. Once you are comfortable with if-else chains, the natural next steps are the switch statement (not tested on the AP exam but common in professional Java), the ternary operator, and the interplay between selection and iteration via loops guarded by conditions.

Featureif StatementTernary Operator (? :)
Syntaxif (c) { s1; } else { s2; }c ? expr1 : expr2
Can contain statements?Yes — any number of statementsNo — expressions only
Returns a value?No (it is a statement)Yes (it is an expression)
AP Exam statusTested extensivelyNot in AP subset but may appear

When you reach Unit 4 (Iteration), you will see that while and for loops are essentially if statements that repeat: the loop condition is a Boolean guard evaluated before each iteration, and the loop body is the conditional block. Understanding if statements deeply therefore lays the conceptual foundation for all flow control in Java.

Practice Problems

1
Consider the following code segment: int x = 5; if (x > 3) System.out.print("A"); if (x > 4) System.out.print("B"); if (x > 5) System.out.print("C"); What is printed?
2
What is the value of result after this code executes? int a = 10, b = 20; int result = 0; if (a > b) { result = 1; } else if (a == b) { result = 2; } else { result = 3; }
3
Consider the following code: int n = 15; String msg = ""; if (n % 3 == 0) { msg += "Fizz"; } if (n % 5 == 0) { msg += "Buzz"; } What is the value of msg?
PROBLEM 4APPLIED
Write a method public static String season(int month) that returns "Winter" for months 12, 1, 2; "Spring" for 3, 4, 5; "Summer" for 6, 7, 8; and "Fall" for 9, 10, 11. Assume month is always 1–12.
PROBLEM 5CRITICAL THINKING
A student writes the following method to classify a BMI value: public static String classify(double bmi) { String result = ""; if (bmi < 18.5) result = "Underweight"; if (bmi < 25.0) result = "Normal"; if (bmi < 30.0) result = "Overweight"; if (bmi >= 30.0) result = "Obese"; return result; } (a) Explain why this method does not work correctly for a bmi of 17.0. What value is returned and what should be returned? (b) Explain why this method does not work correctly for a bmi of 22.0. What value is returned and what should be returned? (c) Rewrite the method body using a correct if-else if-else structure. (d) Explain in one or two sentences the general principle that the student violated.
Varsity Tutors • AP Computer Science A • if Statements