The if Statement
What you'll learn: How to use an if statement to execute code only when a specific condition is true.
The Core Idea
An if statement is your program's decision-maker. It checks whether a Boolean expression is true, and if so, runs a block of code. If the condition is false, the code block is simply skipped, and your program continues past it.
Think of it like an automatic door sensor: if someone approaches, then the door opens. No person? The door stays closed. Your code works the same way—it only acts when the condition you specify is met.
Basic Syntax
if (condition) {
// code to run when condition is true
}
The condition is any Boolean expression (using comparison or logical operators you've learned). The curly braces {} contain the code that executes only when the condition evaluates to true.
Examples
if (temperature > 30) {
print("It's hot outside!")
}
Here, the message only prints when temperature is greater than 30.
if (age >= 18 && hasLicense) {
print("You can drive")
}
This code runs only if both conditions are true (using the logical AND operator && you learned earlier).
What Happens Next?
After the if statement—whether its block ran or not—execution continues with whatever code comes after. The if doesn't stop your program; it just optionally inserts some behavior based on a condition.
Key Takeaway: An if statement runs its code block only when the Boolean condition is true, allowing your program to make decisions and respond to different situations.