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

The if Statement: Basic Conditional Execution

Learn how to use if to execute code only when a boolean condition is true, controlling program flow based on runtime values.

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

  1. Java evaluates the boolean expression in parentheses
  2. If the result is true, the code block executes
  3. If the result is false, Java skips the entire block
  4. 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.