---
title: "AP CSA 2.3: if Statements and Control Flow"
description: "Learn how if and if-else statements control program flow in AP Computer Science A. Covers one-way and two-way selection, tracing conditions, and common Java errors."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO"
type: "study-guide"
subject: "AP Computer Science A"
unit: "Unit 2 – Selection and Iteration"
lastUpdated: "2026-06-09"
---

# AP CSA 2.3: if Statements and Control Flow

## Summary

Learn how if and if-else statements control program flow in AP Computer Science A. Covers one-way and two-way selection, tracing conditions, and common Java errors.

## Guide

An `if` statement is a selection statement that changes the normal top-to-bottom flow of a program by running a [block of code](/ap-comp-sci-a/unit-3/scope-and-access/study-guide/56FUK4RSofr7slzwm6xm "fv-autolink") only when a Boolean expression is true. One-way selection uses `if`, while two-way selection uses `if-else` to choose between two blocks. For [AP Computer Science A](/ap-comp-sci-a "fv-autolink"), trace conditions in order and identify exactly which block runs.

## Why This Matters for the AP Computer Science A Exam

[Selection](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe "fv-autolink") is one of the three core building blocks of [algorithms](/ap-comp-sci-a/key-terms/algorithm "fv-autolink"), 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](/ap-comp-sci-a/unit-1/variables-and-primitive-data-types/study-guide/rezA6f3hJz84TKaY5Jjl "fv-autolink") (true or false).
- When [tracing](/ap-comp-sci-a/key-terms/tracing "fv-autolink"), 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](/ap-comp-sci-a/key-terms/relational-operator "fv-autolink") (`==`, `!=`, `<`, `>`, `<=`, `>=`) and Boolean variables comes in. An `if` statement is a selection statement that changes the [flow of control](/ap-comp-sci-a/unit-1/creating-and-storing-objects/study-guide/rUOTKl6Ih5noXJ0GtxJF "fv-autolink") 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](/ap-comp-sci-a/key-terms/expression "fv-autolink") 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](/ap-comp-sci-a/key-terms/compile "fv-autolink") 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](/ap-comp-sci-a/key-terms/reference-type "fv-autolink"), `==` compares whether the two variables refer to the same [object](/ap-comp-sci-a/key-terms/object "fv-autolink"), 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](/ap-comp-sci-a/key-terms/object-reference "fv-autolink"), 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.

## Related AP Computer Science A Guides

- [2.1 Algorithms with Selection and Repetition](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe)
- [2.7 While Loops](/ap-comp-sci-a/unit-2/while-loops/study-guide/7qGsGOh1UKALAWpJhZOi)
- [2.6 Equivalent Boolean Expressions](/ap-comp-sci-a/unit-2/equivalent-boolean-expressions/study-guide/aMDnyFuOcAXnZigLW1vL)
- [2.11 Nested Iteration](/ap-comp-sci-a/unit-2/nested-iteration/study-guide/Buapg1KURHNbw6yRY8EZ)
- [2.12 Informal Code Analysis](/ap-comp-sci-a/unit-2/informal-code-analysis/study-guide/CR84MbOE4FDDoSVokDVZ)
- [2.8 For Loops](/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt)

## Vocabulary

- **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.

## FAQs

### 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.

## Structured Data

```json
{"@context":"https://schema.org","@type":"FAQPage","inLanguage":"en","mainEntity":[{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO#what-is-an-if-statement-in-java","name":"What is an if statement in Java?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO#what-is-one-way-selection","name":"What is one-way selection?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO#what-is-two-way-selection","name":"What is two-way selection?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO#what-must-an-if-condition-evaluate-to","name":"What must an if condition evaluate to?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO#why-do-curly-braces-matter-in-if-statements","name":"Why do curly braces matter in if statements?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/if-statements-and-control-flow/study-guide/IbxsFeJQ5T1FNNBEWErO#how-are-if-statements-tested-on-the-ap-csa-exam","name":"How are if statements tested on the AP CSA exam?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}
```
