Get startedGet started for free

Else, else if

1. Else, else if

We just saw how `if` statements help us run code only when a condition is true. But what `if` we want our program to take different actions depending on different conditions? That's where `else if` and `else` come in.

2. Multiple ifs

Let's go back to the grading example. If a student gets a score above 90, we want to print `“Excellent!”`. But if they get above 70, maybe we want to print `“Good effort.”` And if the score is lower than that, we want to show “Keep trying!” Using multiple if statements for this can get messy because each one runs independently.

3. if - else if - else

Instead, we can build a workflow using `if`, `else if`, and `else`. This way, Java checks each condition in order, and as soon as one of them is true, it runs that block and skips the rest. Here's how it works. We start with an `if` statement to check the first condition. If that's not true, Java moves to the `else if` and checks the next one. If none of the conditions are true, the `else` block runs as a final fall back. Note how each block of code is enclosed in curly brackets - they tell Java what code should be executed for each condition.

4. Only one block is run

This structure helps us write clear, readable logic. Only one block of code runs from the entire `if–else if–else` chain, which keeps our program from doing multiple things when we only want one.

5. As many as we need - just be careful about the order

We can chain together as many else if blocks as we need. We just need to make sure each one checks a different condition and that they appear in the right order. For example, we always want to check higher scores first so that a score of 95 doesn’t get caught by a lower condition like “greater than 70” before reaching the more appropriate one.

6. Recap

Using else if and else helps us control the flow of our program based on multiple possibilities. It's a simple but powerful way to build logic that reacts to the data we're working with.

7. Let's practice!

Now, you'll write a program that responds to different situations based on input. Let's give it a try!