AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

3.3 If-Else Statements

Verified for the 2025 AP Computer Science A examCitation:

Building on our knowledge of if statements, we now turn to if-else statements, which provide more powerful decision-making capabilities in your programs. While simple if statements allow us to execute code when a condition is true, if-else statements enable us to handle both true and false conditions elegantly. This two-way selection is a fundamental concept in programming that lets your code take different paths based on different situations, making your programs more responsive and versatile.

Two-Way Selection with if-else

Two-way selection means that our code will follow one of two paths: one path when a condition is true, and another path when the condition is false. This is implemented using an if-else statement.

if (condition) {
    // Code executed when condition is true
} else {
    // Code executed when condition is false
}

Basic Structure and Syntax

The if-else statement consists of:

  • An if keyword followed by a condition in parentheses
  • A block of code in curly braces to execute when the condition is true
  • An else keyword
  • A block of code in curly braces to execute when the condition is false
if (temperature >= 70) {
    System.out.println("It's warm outside. Wear light clothes.");
} else {
    System.out.println("It's cool outside. Bring a jacket.");
}

In this example:

  • If the temperature is 70 or higher, it prints the "warm outside" message
  • If the temperature is below 70, it prints the "cool outside" message
  • Exactly one of these two code blocks will always execute

How if-else Statements Work

When Java encounters an if-else statement:

  1. It evaluates the condition in the parentheses after the if keyword
  2. If the condition is true, it executes the code in the first block (after the if)
  3. If the condition is false, it skips the first block and executes the code in the second block (after the else)
  4. After executing either block, the program continues with the code after the entire if-else statement
int hour = 14; // 2 PM in 24-hour format
if (hour < 12) {
    System.out.println("Good morning!");
} else {
    System.out.println("Good afternoon!");
}
System.out.println("Have a nice day!"); // This always executes

In this example, "Good afternoon!" will be printed because the hour (14) is not less than 12. Then "Have a nice day!" will be printed regardless of the time.

Comparing One-Way and Two-Way Selection

One-Way Selection (if)Two-Way Selection (if-else)
if (condition) { code... }if (condition) { code... } else { code... }
Code executes only when condition is trueCode executes for both true and false conditions
If condition is false, nothing special happensIf condition is false, the else block executes
Can leave certain situations unhandledEnsures all cases are handled

Examples of if-else in Action

Example 1: Determining Pass/Fail

int score = 75;
if (score >= 60) {
    System.out.println("You passed the exam!");
} else {
    System.out.println("You failed the exam. Please study and try again.");
}

Example 2: Checking Even/Odd Numbers

int number = 7;
if (number % 2 == 0) {
    System.out.println(number + " is an even number.");
} else {
    System.out.println(number + " is an odd number.");
}

Example 3: Setting a Maximum Value

int value = 120;
int maxAllowed = 100;
if (value > maxAllowed) {
    value = maxAllowed;
    System.out.println("Value was capped at maximum.");
} else {
    System.out.println("Value is within acceptable range.");
}
System.out.println("Final value: " + value);

Common Patterns with if-else

1. Setting Default Values

String userColor = getUserInput();
String backgroundColor;

if (userColor != null && !userColor.isEmpty()) {
    backgroundColor = userColor; // Use user's preference
} else {
    backgroundColor = "white"; // Default value
}

2. Validating Input

int age = getUserAge();

if (age >= 0 && age <= 120) {
    // Process valid age
    calculateInsurance(age);
} else {
    // Handle invalid input
    System.out.println("Error: Please enter a valid age between 0 and 120.");
}

3. Swapping Values

// Ensure x is always smaller than y
if (x > y) {
    // Swap the values
    int temp = x;
    x = y;
    y = temp;
} else {
    // Values are already in the desired order
    // No action needed
}

Style and Best Practices

  1. Always use curly braces: Even for single-line statements, using braces improves readability and prevents bugs.
// Good practice
if (isRaining) {
    takeUmbrella = true;
} else {
    takeUmbrella = false;
}

// Risky - avoid this style

if (isRaining) takeUmbrella = true;
else takeUmbrella = false;
  1. Simplify boolean assignments: When assigning boolean values based on conditions, you can often simplify.
// Instead of this:
if (age >= 18) {
    isAdult = true;
} else {
    isAdult = false;
}

// You can write:
isAdult = (age >= 18);
  1. Indent properly: Consistent indentation makes your code easier to read.
// Properly indented
if (condition) {
    statement1;
    statement2;
} else {
    statement3;
    statement4;
}

Common Mistakes with if-else

Confusing == and =

// INCORRECT - assigns value instead of comparing

if (temperature = 70) { // This always evaluates to true if 70 is non-zero
    System.out.println("It's exactly 70 degrees.");
}

// CORRECT - compares values

if (temperature == 70) {
    System.out.println("It's exactly 70 degrees.");
}

Forgetting Curly Braces

// INCORRECT - missing braces can lead to unexpected behavior

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.");
} else {
    System.out.println("Enjoy the sunshine!");
}

Dangling else Problem

In nested if statements, an else is associated with the closest preceding if that doesn't already have an else.

// Ambiguous without braces
if (x > 0)
    if (y > 0)
        System.out.println("Both x and y are positive");
else
    System.out.println("x is not positive"); // This else belongs to which if?

// Clear with braces
if (x > 0) {
    if (y > 0) {
        System.out.println("Both x and y are positive");
    }
} else {
    System.out.println("x is not positive"); // Clearly belongs to the outer if
}

Efficient Boolean Logic

Sometimes, you can simplify if-else statements that assign boolean values:

// This code:
boolean isEligibleForDiscount;
if (age <= 12 || age >= 65) {
    isEligibleForDiscount = true;
} else {
    isEligibleForDiscount = false;
}

// Can be simplified to:
boolean isEligibleForDiscount = (age <= 12 || age >= 65);

Key Takeaways

  • if-else statements provide two-way selection, executing one code block when a condition is true and another when it's false
  • Exactly one of the two code blocks will always execute
  • Always use curly braces and proper indentation for readability and to prevent logic errors

Key Terms to Review (2)

Brackets: Brackets are symbols used in programming to enclose and group together elements, such as variables or expressions, within a statement. They are typically represented by the characters "[" and "]".
If-else statement: An if-else statement is a programming construct that allows the program to make decisions based on certain conditions. It checks a condition and executes one block of code if the condition is true, and another block of code if the condition is false.