The if Statement: Basic Conditional Execution
What you'll learn: How to make your program execute code only when a specific condition is met.
Until now, every line of code in your programs has run sequentially, one after another. The if statement changes that by letting you say: "Only run this code if something is true."
The Core Idea
Think of an if statement like a bouncer at a door. If you meet the requirement (the condition is true), you get in and the code executes. If you don't (the condition is false), you skip right past it.
The basic syntax looks like this:
if (booleanExpression) {
// code to execute only if true
}
The booleanExpression must evaluate to true or false—exactly what you learned with the boolean type and comparison operators.
Simple Examples
int temperature = 95;
if (temperature > 90) {
temperature = temperature - 5; // only runs if temp > 90
}
// temperature is now 90
boolean isRaining = true;
if (isRaining) {
// bring umbrella code would go here
}
int age = 16;
if (age >= 18) {
// This block is skipped because 16 >= 18 is false
}
// Program continues here
The condition uses the relational and logical operators you've learned: ==, !=, <, >, <=, >=, &&, ||, and !.
How It Works
- Java evaluates the boolean expression in parentheses
- If the result is
true, the code block executes - If the result is
false, Java skips the entire block - Execution continues with whatever comes after
Key Takeaway: The if statement controls program flow by executing code blocks only when a boolean condition evaluates to true, letting your program make decisions based on runtime values.