Fiveable
Fiveable
scoresvideos
AP Computer Science A
One-page, printable cheatsheet
Cheatsheet visualization
Table of Contents

💻ap computer science a review

3.2 If Statements and Control Flow

Verified for the 2025 AP Computer Science A examCitation:

In programming, we often need our code to make decisions based on different conditions. This is where conditional statements come in, allowing our programs to execute different blocks of code depending on whether certain conditions are true or false. The if statement is one of the most fundamental control structures in Java and other programming languages. By understanding how to use if statements effectively, you'll be able to create programs that respond intelligently to different inputs and situations, making your code more dynamic and useful.

Program Control Flow

Control flow refers to the order in which statements are executed in a program. By default, Java executes statements sequentially (one after another, from top to bottom). However, conditional statements like if allow us to interrupt this sequential flow and create branches in our code.

Sequential Flow:          Branching Flow:
┌─────────────┐           ┌─────────────┐
│ Statement 1 │           │ Statement 1 │
└─────────────┘           └─────────────┘
       ↓                         ↓
┌─────────────┐           ┌─────────────┐
│ Statement 2 │           │ Condition?  │──→ True ──→┌─────────────┐
└─────────────┘           └─────────────┘            │ Statement A │
       ↓                         │                   └─────────────┘
┌─────────────┐                  │                         ↓
│ Statement 3 │                  └──→ False ─→┌─────────────┐
└─────────────┘                                │ Statement B │
                                               └─────────────┘

Basic if Statement Structure

The simplest form of the if statement executes a block of code only if a specified condition is true:

if (condition) {
    // code to execute when condition is true
}

For example:

int temperature = 75;

if (temperature > 70) {
    System.out.println("It's a warm day!");
}

In this example, "It's a warm day!" will only be printed if the temperature is greater than 70.

How if Statements Work

  1. The condition inside the parentheses is evaluated to determine if it's true or false
  2. If the condition is true, the code block within the curly braces {} is executed
  3. If the condition is false, the code block is skipped entirely
  4. Program execution continues with the code after the if block

if-else Statements

The if-else structure allows you to execute one block of code if the condition is true and a different block if it's false:

if (condition) {
    // code to execute when condition is true
} else {
    // code to execute when condition is false
}

Example:

int score = 85;

if (score >= 60) {
    System.out.println("You passed!");
} else {
    System.out.println("You failed. Try again.");
}

Since 85 is greater than or equal to 60, this code will print "You passed!"

if-else-if Ladder

When you need to check multiple conditions, you can use an if-else-if ladder:

if (condition1) {
    // code to execute when condition1 is true
} else if (condition2) {
    // code to execute when condition1 is false but condition2 is true
} else if (condition3) {
    // code to execute when condition1 and condition2 are false but condition3 is true
} else {
    // code to execute when all conditions are false
}

Example (grading system):

int score = 85;
char 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';
}

System.out.println("Your grade is: " + grade);

With a score of 85, this code will assign 'B' to the grade variable and print "Your grade is: B".

Nested if Statements

You can place an if statement inside another if statement to create nested conditions:

if (outerCondition) {
    // code for when outerCondition is true
    
    if (innerCondition) {
        // code for when both outerCondition and innerCondition are true
    }
}

Example:

int age = 25;
boolean hasLicense = true;

if (age >= 16) {
    System.out.println("Age requirement met.");
    
    if (hasLicense) {
        System.out.println("You can drive a car.");
    } else {
        System.out.println("You need to get a license first.");
    }
} else {
    System.out.println("You're too young to drive.");
}

One-Way Selection

When we have a single if statement without an else clause, this is called "one-way selection." The code block executes only when the condition is true; otherwise, it's skipped entirely.

if (temperature < 32) {
    System.out.println("Warning: Freezing temperatures!");
}
// Program continues here regardless of the condition

This is useful when you only need to take an action in one specific case and do nothing special otherwise.

Common Mistakes with if Statements

1. Forgetting curly braces

If you omit curly braces, only the first statement after the condition is controlled by the if:

// INCORRECT (if you intended both lines to be controlled by the condition)
if (isRaining)
    System.out.println("Take an umbrella.");
    System.out.println("Wear a raincoat.");  // This always executes regardless of isRaining!

// CORRECT
if (isRaining) {
    System.out.println("Take an umbrella.");
    System.out.println("Wear a raincoat.");
}

2. Using assignment (=) instead of equality (==)

// INCORRECT - this assigns true to isRaining and then evaluates to true

if (isRaining = true) {
    System.out.println("Take an umbrella.");
}

// CORRECT - this checks if isRaining equals true

if (isRaining == true) {
    System.out.println("Take an umbrella.");
}

// Or better yet, simply:
if (isRaining) {
    System.out.println("Take an umbrella.");
}

3. Unnecessary boolean comparisons

// Redundant
if (isRaining == true) {
    System.out.println("Take an umbrella.");
}

// Cleaner
if (isRaining) {
    System.out.println("Take an umbrella.");
}

// Redundant
if (isRaining == false) {
    System.out.println("Leave umbrella at home.");
}

// Cleaner
if (!isRaining) {
    System.out.println("Leave umbrella at home.");
}

Conditional Statements and Program Flow

Conditional statements are powerful because they alter the normal sequential flow of a program. Here's how different control structures affect program flow:

Control StructureEffect on Program Flow
SequentialStatements executed in order, top to bottom
Selection (if)Program chooses between different paths based on conditions
Iteration (loops)Program repeats a section of code multiple times

Style Guidelines for if Statements

When writing if statements, follow these best practices:

  • Always use curly braces, even for single-line blocks
  • Indent the code inside the curly braces for readability
  • Use meaningful conditions that clearly express your intent
  • Consider using compound conditions when appropriate
  • Keep conditions as simple as possible for readability
// Good style
if (age >= 18 && hasValidID) {
    isEligibleToVote = true;
}

Key Takeaways

  • if statements allow your program to make decisions based on conditions
  • The basic forms are: if, if-else, and if-else-if
  • Conditional statements interrupt the sequential flow of execution
  • A one-way selection (if without else) is used when you only need to take action in one specific case
  • Always use curly braces to clearly define the scope of your if statements

Key Terms to Review (5)

Block of Code: A block of code refers to a group of statements that are grouped together and treated as a single unit. It is often used to organize and control the flow of execution in a program.
Conditional Statement: A conditional statement is a programming construct that allows the execution of certain code blocks based on whether a specific condition is true or false.
Indentation: Indentation refers to adding spaces or tabs at the beginning of lines of code to visually organize and structure it. In Python, indentation plays an important role in defining blocks of code within control structures like loops and conditionals.
Method: A method is a named sequence of instructions that can be called or invoked to perform a specific task or action. Methods are used for code reusability, organization, and abstraction.
Return Statement: A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.