Course contentsShow
← Java
Lesson 135 of 2,8704. Control Flow StructuresFree lesson

The else Clause: Handling the Alternative Path

Understand how else provides an alternative execution path when the if condition is false, creating binary branching logic.

The else Clause: Handling the Alternative Path

What you'll learn: How to use else to execute different code when an if condition is false, creating a two-way decision in your program.

The Fork in the Road

You've learned that if lets you execute code when a condition is true. But what happens when it's false? The else clause gives you a way to handle that alternative path. Think of it like a fork in the road: if one condition is met, go left; otherwise, go right. There's no "do nothing" option—one path will be taken.

Binary Branching Logic

The if-else structure creates binary branching: exactly two possible execution paths. When the boolean expression in the if evaluates to false, Java automatically jumps to the else block instead.

int temperature = 55;

if (temperature > 70) {
    System.out.println("It's warm outside!");
} else {
    System.out.println("It's cool outside!");
}
// Output: It's cool outside!

Here, since 55 > 70 is false, the if block is skipped and the else block runs instead.

One or the Other, Never Both

It's crucial to understand: either the if block executes or the else block executes, but never both. Every time your program reaches an if-else statement, exactly one branch runs.

boolean isRaining = false;

if (isRaining) {
    System.out.println("Bring an umbrella.");
} else {
    System.out.println("Enjoy the sunshine!");
}
// Output: Enjoy the sunshine!

The else clause is optional—you can use if alone—but when you need to handle both outcomes explicitly, else is your tool.

Key Takeaway: The else clause provides an alternative execution path when the if condition is false, ensuring one of two code blocks always runs in a binary decision structure.