Fiveable

💻AP Computer Science A Unit 2 Review

QR code for AP Computer Science A practice questions

2.3 If Statements and Control Flow

2.3 If Statements and Control Flow

Written by the Fiveable Content Team • Last updated June 2026
Verified for the 2027 exam
Verified for the 2027 examWritten by the Fiveable Content Team • Last updated June 2026
💻AP Computer Science A
Unit & Topic Study Guides

Frequently Asked Questions

Previous Exam Prep

Study Tools

Exam Skills

AP Cram Sessions 2021

Pep mascot

An if statement is a selection statement that changes the normal top to bottom flow of a program by running a block of code only when a Boolean expression is true. A one way selection ( if ) runs its body just when the condition is true, while a two way selection ( if else ) picks between two blocks: the if body runs when the condition is true, and the else body runs when it is false. Topic 2.3, If Statements and Control Flow is part of AP Computer Science A in Unit 2 - Selection and Iteration.

Why This Matters for the AP Computer Science A Exam

Selection is one of the three core building blocks of algorithms, alongside sequencing and repetition, so if statements show up across the whole course. On the multiple-choice section, you will often trace code segments to figure out what prints or what a variable equals after the conditions are checked. On the free-response section, code-writing questions frequently ask you to implement methods that make decisions, which means choosing the right if or if-else structure and writing valid Java conditions. Getting comfortable now pays off later when selection gets combined with loops, strings, arrays, and class methods.

Key Takeaways

  • Selection statements interrupt sequential execution and run different code based on a Boolean expression.
  • A one-way selection (if) runs its body only when the condition is true, otherwise the body is skipped.
  • A two-way selection (if-else) runs the if body when the condition is true and the else body when it is false; exactly one of the two runs.
  • The condition in parentheses must evaluate to a Boolean value (true or false).
  • When tracing, check conditions in order and only enter a block when its condition is true.
  • Use .equals() to compare String contents, and use ==/!= for primitive values.

Key Concepts

The if Statement Structure

An if statement starts with the keyword if, followed by a Boolean condition in parentheses, then a block of code in curly braces. The basic form looks like this:

</>Java
if (condition) {
    // statements to execute when condition is true
}

The condition must evaluate to true or false. That is where your work with relational operators (==, !=, <, >, <=, >=) and Boolean variables comes in. An if statement is a selection statement that changes the flow of control by running different segments of code based on the value of a Boolean expression.

How Code Blocks Execute

When the program reaches an if statement, it evaluates the Boolean condition first. If the condition is true, the program runs every statement inside the curly braces. If the condition is false, the program skips the entire block and continues with the next line after the closing brace.

Your program follows a specific path based on whether each condition is true or false. Tracing that path carefully is exactly the skill multiple-choice questions test.

One-Way vs Two-Way Selection

A one-way selection is a plain if statement, used when there is a segment of code to run under a certain condition. The body runs only when the Boolean expression is true; otherwise nothing extra happens.

A two-way selection is an if-else statement, used when there are two segments of code: one for when the condition is true and one for when it is false. The if body runs when the expression is true, and the else body runs when the expression is false. Exactly one of the two blocks runs.

</>Java
if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

Single Statement vs Block Statements

Java lets you write an if without curly braces when there is only one statement, but it is safer to always include the braces. Without braces, only the single statement right after the condition belongs to the if. Any statement after that runs no matter what, which leads to logic bugs that are hard to spot.

Nested if Statements

You can place an if statement inside another if statement to check related conditions in layers. The inner condition is only checked when the outer condition is true, which creates a hierarchy of decisions. Nested selection gets its own focused treatment in a later topic, so think of this as a preview.

Code Examples

</>Java
// Basic if statements with different condition types
public class BasicIfStatements {
    public static void main(String[] args) {
        int temperature = 75;
        boolean isRaining = false;
        String weather = "sunny";

        // Numeric comparison
        if (temperature > 70) {
            System.out.println("It's warm outside!");
            System.out.println("Perfect weather for a walk.");
        }

        // Boolean variable check
        if (isRaining) {
            System.out.println("Don't forget your umbrella!");
        }

        // String comparison using equals
        if (weather.equals("sunny")) {
            System.out.println("Great day for outdoor activities!");
        }

        // This runs no matter what the conditions above did
        System.out.println("Weather check complete.");
    }
}

Here is a two-way selection using if-else:

</>Java
// if-else chooses exactly one of two blocks
public class AccessCheck {
    public static void main(String[] args) {
        int age = 16;

        if (age >= 18) {
            System.out.println("Adult access granted");
        } else {
            System.out.println("Limited access granted");
        }

        System.out.println("Check complete");
    }
}

Nested if statements check related conditions in layers:

</>Java
// Nested if statements
public class GradeCheck {
    public static void main(String[] args) {
        int score = 85;
        boolean attendedClass = true;

        if (score >= 70) {
            System.out.println("Score meets minimum requirement");

            // Inner condition only checked because outer was true
            if (attendedClass) {
                System.out.println("Attendance requirement met");
            }
        }

        System.out.println("Grade check finished");
    }
}

Common Errors and Debugging

Missing curly braces Without braces, only the first statement is part of the if. The line after it always runs.

</>Java
// Risky - only the first println belongs to the if

if (score >= 90)
    System.out.println("Excellent work!");
    System.out.println("You earned an A!"); // This ALWAYS runs

// Safe - both statements are grouped

if (score >= 90) {
    System.out.println("Excellent work!");
    System.out.println("You earned an A!"); // Only runs when condition is true
}

Using = instead of == A single = is assignment, not comparison. In a Boolean condition this will not compile in Java.

</>Java
int x = 5;

// Wrong - assignment in a boolean context does not compile

// if (x = 10) { ... }

// Right - compares x to 10

if (x == 10) {
    System.out.println("x equals 10");
}

Comparing Strings with == Use .equals() to compare String contents. With reference types, == compares whether the two variables refer to the same object, not whether the text matches.

</>Java
String weather = "sunny";

// Correct way to compare String contents
if (weather.equals("sunny")) {
    System.out.println("Matches");
}

Variable scope inside blocks A variable declared inside an if block only exists inside that block.

</>Java
if (true) {
    int localVar = 10; // exists only inside this block
    System.out.println(localVar);
}
// System.out.println(localVar); // Error - localVar is out of scope here

// Declare before the if if you need it afterward
int sharedVar = 0;
if (true) {
    sharedVar = 10;
}
System.out.println(sharedVar); // prints 10

Practice Problems

Problem 1: Pass or fail Write a method that prints "Pass" if a score is at least 60 and "Fail" otherwise. Use a two-way selection.

</>Java
public static void reportResult(int score) {
    // Your solution here
}

Solution:

</>Java
public static void reportResult(int score) {
    if (score >= 60) {
        System.out.println("Pass");
    } else {
        System.out.println("Fail");
    }
}

Problem 2: Grade assignment Write a method that prints a letter grade based on a numeric score using separate if statements: A (90+), B (80-89), C (70-79), F (below 70).

</>Java
public static void assignGrade(int score) {
    // Your solution here
}

Solution:

</>Java
public static void assignGrade(int score) {
    if (score >= 90) {
        System.out.println("Grade: A");
    }
    if (score >= 80 && score < 90) {
        System.out.println("Grade: B");
    }
    if (score >= 70 && score < 80) {
        System.out.println("Grade: C");
    }
    if (score < 70) {
        System.out.println("Grade: F");
    }
}

Problem 3: Membership message Write a method that prints "Member" when isMember is true and "Guest" when it is false.

</>Java
public static void greet(boolean isMember) {
    // Your solution here
}

Solution:

</>Java
public static void greet(boolean isMember) {
    if (isMember) {
        System.out.println("Member");
    } else {
        System.out.println("Guest");
    }
}

How to Use This on the AP Computer Science A Exam

Code Tracing

Multiple-choice questions often hand you a code segment and ask what prints or what a variable equals after the conditions run. Check each condition in order, decide whether its block runs, and update your traced values as you go. Watch for answer choices that show what would happen if a different condition were true or if a skipped block had executed.

Free Response

Code-writing questions frequently ask you to write methods that make decisions. Pick a one-way if when you only act under one condition, and an if-else when you must choose between two outcomes. Always use curly braces so your blocks are unambiguous, and make sure your condition evaluates to a Boolean value.

Common Trap

When if statements are nested, the inner condition is only checked when the outer condition is true. Do not evaluate every condition as if they were independent. Trace the outer condition first, and only step inside when it is true.

Common Misconceptions

  • "An if with a false condition runs the next line anyway." Without braces, only the single statement directly after the condition is controlled by the if. The lines after it run regardless, which is a bug, not intended behavior. Always use braces.
  • "else runs in addition to the if body." In a two-way selection, exactly one block runs. If the condition is true, only the if body runs; if it is false, only the else body runs.
  • "== compares String text." For reference types like String, == compares object references, not contents. Use .equals() to compare String values.
  • "The condition can be any value." In Java the condition must evaluate to a Boolean (true or false), not a number.
  • "Inner if statements are always checked." A nested inner condition is only evaluated when the outer condition is true.
  • "if and if-else are interchangeable." Use a one-way if when there is a single conditional action and an if-else when there are two mutually exclusive outcomes.

Vocabulary

The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.

Term

Definition

Boolean expression

An expression that evaluates to either true or false, used to control the execution of loops and conditional statements.

branching logical process

Program flow that divides into different paths based on conditional statements, allowing different code to execute depending on whether conditions are true or false.

flow of control

The order in which statements in a program are executed, which can be interrupted by method calls and resumed after the method completes.

if statement

A selection statement that executes a code segment based on whether a Boolean expression is true or false.

if-else statement

A selection statement that provides two alternative code segments: one executed when a Boolean expression is true and another when it is false.

one-way selection

An if statement that executes a code segment only when a Boolean expression is true.

selection statement

Programming statements that control the flow of execution by choosing which code segments to run based on conditions.

sequential execution

The default flow of a program where statements are executed one after another in the order they appear.

two-way selection

An if-else statement that executes one code segment when a Boolean expression is true and a different segment when it is false.

Frequently Asked Questions

What is an if statement in Java?

An if statement is a selection statement that runs code only when a Boolean expression is true. It lets a program choose between different paths instead of running every line in order.

What is one-way selection?

One-way selection uses a plain if statement. The body runs when the condition is true, and the program skips it when the condition is false.

What is two-way selection?

Two-way selection uses an if-else statement. Exactly one branch runs: the if branch when the condition is true, or the else branch when the condition is false.

What must an if condition evaluate to?

The condition inside an if statement must evaluate to a Boolean value: true or false. In Java, non-Boolean values like integers cannot be used as conditions by themselves.

Why do curly braces matter in if statements?

Curly braces group multiple statements into one branch. Without braces, only the next statement is controlled by the if or else, which can make code behave differently than expected.

How are if statements tested on the AP CSA exam?

AP CSA often tests if statements through code tracing, output prediction, and FRQs that require decision logic. You need to know which branch runs and how variable values change.

Pep mascot
Upgrade your Fiveable account to print any study guide

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Click below to go to billing portal → update your plan → choose Yearly→ and select "Fiveable Share Plan". Only pay the difference

Plan is open to all students, teachers, parents, etc
Pep mascot
Upgrade your Fiveable account to export vocabulary

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Plan is open to all students, teachers, parents, etc
report an error
description

screenshots help us find and fix the issue faster (optional)

add screenshot

2,589 studying →