Verified for the 2025 AP Computer Science A exam•Citation:
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 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 }
The if-else statement consists of:
if
keyword followed by a condition in parentheseselse
keywordif (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:
When Java encounters an if-else statement:
if
keywordtrue
, it executes the code in the first block (after the if)false
, it skips the first block and executes the code in the second block (after the else)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.
One-Way Selection (if) | Two-Way Selection (if-else) |
---|---|
if (condition) { code... } | if (condition) { code... } else { code... } |
Code executes only when condition is true | Code executes for both true and false conditions |
If condition is false, nothing special happens | If condition is false, the else block executes |
Can leave certain situations unhandled | Ensures all cases are handled |
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."); }
int number = 7; if (number % 2 == 0) { System.out.println(number + " is an even number."); } else { System.out.println(number + " is an odd number."); }
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);
String userColor = getUserInput(); String backgroundColor; if (userColor != null && !userColor.isEmpty()) { backgroundColor = userColor; // Use user's preference } else { backgroundColor = "white"; // Default value }
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."); }
// 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 }
// Good practice if (isRaining) { takeUmbrella = true; } else { takeUmbrella = false; } // Risky - avoid this style if (isRaining) takeUmbrella = true; else takeUmbrella = false;
// Instead of this: if (age >= 18) { isAdult = true; } else { isAdult = false; } // You can write: isAdult = (age >= 18);
// Properly indented if (condition) { statement1; statement2; } else { statement3; statement4; }
// 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."); }
// 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!"); }
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 }
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);