1. If statements
So far, we've been writing code that runs step by step, with every line executed in order. However, in most real programs, we need our code to perform different operations depending on the situation. This is where control flow comes in.
2. Control flow
The simplest form of control flow is the if statement. It lets us say: "If a certain condition is true, then run this part of the code." Otherwise, Java just skips over it.
3. How if statements work
Let's say we're building a grading system. If a student's score is 90 or higher, we want to print `"Great job!"`. We don't want that message to show up all the time - only when the score meets that condition. That's exactly what an if statement allows us to do.
4. if statement anatomy
The syntax is straightforward: we start with the keyword `if`, then put a condition inside parentheses, followed by a block of code in curly brackets. If the condition is true, Java runs the code inside the curly brackets.
5. Conditions
To write these conditions, we use comparison operators like equal to, not equal, less than and greater than, and less or equal to and greater or equal to. These let us compare values to decide which code should run.
For example, we might write: `if score >= 90`, then print a congratulatory message. If the condition isn't met, Java simply skips the message.
6. if and if and if ...
We can also have multiple if statements in a row. That way, we can print different messages depending on the value of the score. For example, we might show `“Excellent!"` for scores over 90, `“Good job!”` for scores over 70, and `“Try again!”` for lower scores. Each condition is checked separately and in their order, and only the matching ones will run. Note how here, both `“Excellent!”` and `“Good job!”` are displayed because the value is more than 90 and 70 - that's something we'll address in the next video.
7. Recap
Conditionals allow us to make our code more dynamic and responsive - they're a key part of writing real-world logic. We can use any of the comparison operators we've encountered so far such as greater than or less or equal to.
8. Let's practice!
Next, you'll write your own if statement to check a condition and run code only when that condition is true. Let's try it out!