Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

if Statements

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, if statements let your program make decisions. If a condition is true, the code does one thing; otherwise, it can do something else or nothing at all.

Why this matters

Imagine you're getting ready to leave for school. You glance out the window. Is it raining? This simple question creates a fork in your morning routine. If the answer is yes, you grab your umbrella. If the answer is no, you leave it behind. You just ran a program in your head.

Decision-making flow for a rainy morning.

Your brain automatically evaluated a condition (is it raining?) and chose an action based on the outcome. Our code needs to do this all the time. What if a user tries to log in with the wrong password? What if a player in a game runs out of health? What if a customer's shopping cart total qualifies for free shipping?

In this lesson, we'll learn how to give our programs this decision-making power using if statements. We'll start with simple one-way choices and then build up to the two-way "if this, then that, otherwise do this other thing" logic you use every day.

Concept overview

flowchart TD
    A[Start] --> B{Is cart total > $75?};
    B -- Yes --> C[Set shipping to $0];
    B -- No --> D[Keep standard shipping cost];
    C --> E[End];
    D --> E[End];
This diagram shows a flowchart for an if-else decision. It starts, then a diamond-shaped node asks "Is cart total > $75?". A "Yes" branch leads to a box "Set shipping to $0", and a "No" branch leads to a box "Keep standard shipping cost". Both branches then merge into an "End" node.

Core explanation

Think of a simple program as a recipe. You follow the steps in order, from first to last, without skipping.

  1. Preheat oven to 350°F.
  2. Mix flour and sugar.
  3. Bake for 30 minutes.

This is called sequential execution. It’s the default behavior of your code. But what if you need to make a choice? What if the recipe said, "If you're making a chocolate cake, add cocoa powder"? That's a decision point. In Java, we create these decision points with if statements.

The One-Way if Statement

A one-way if statement is for when you only need to do something extra under a specific condition. If the condition isn't met, you just move on.

Think about an online store. They might offer free shipping for orders over $75.

The logic is: If the cart total is greater than $75, then set the shipping cost to $0. If it's not, you do... nothing. The shipping cost just stays what it was.

One-way `if` statement for free shipping.

Here’s how that looks in Java:

double cartTotal = 82.50;
double shippingCost = 5.99;

// Check if the condition is true
if (cartTotal > 75.00) {
  // This code ONLY runs if the condition is true
  System.out.println("Congrats! You qualify for free shipping.");
  shippingCost = 0.00;
}

// This line runs regardless, after the if statement is done
System.out.println("Your shipping cost is: $" + shippingCost);

Let's break it down:

  1. if: This is the keyword that starts the selection statement.
  2. (cartTotal > 75.00): This is the Boolean expression, our condition. It must evaluate to either true or false. Here, since 82.50 is greater than 75.00, it evaluates to true.
  3. { ... }: These curly braces define the body of the if statement. Any code inside this block will only execute when the condition is true.
  4. Because the condition was true, the code inside the braces runs. It prints the "Congrats!" message and sets shippingCost to 0.00. The final output will be "Your shipping cost is: $0.0".

What if cartTotal was $50.00? The condition 50.00 > 75.00 would be false. The entire block of code inside the curly braces would be skipped. The program would jump right to the final System.out.println, and the output would be "Your shipping cost is: $5.99".

The Two-Way if-else Statement

Sometimes, doing nothing isn't enough. You need to provide an alternative action. This is a two-way choice: if the condition is true, do one thing; otherwise (else), do a different thing.

Let's check if a student, Priya, is old enough to vote. The voting age in the US is 18.

The logic is: If Priya's age is 18 or greater, then print "You are eligible to vote." Else (otherwise), print "You are not yet eligible to vote."

This creates two distinct paths. Priya is either eligible or she isn't. One of these two things must be true.

Here’s the Java code:

int priyasAge = 17;

if (priyasAge >= 18) {
  // This is the "true" path
  System.out.println("You are eligible to vote.");
} else {
  // This is the "false" path
  System.out.println("You are not yet eligible to vote.");
}

// The program continues here after one of the above blocks has run.

Let's trace this:

  1. The condition is priyasAge >= 18.
  2. Since priyasAge is 17, the expression 17 >= 18 evaluates to false.
  3. Because the condition is false, the program skips the if block.
  4. It moves to the else keyword and executes the code in the else block.
  5. The output will be "You are not yet eligible to vote."

If priyasAge were 25, the condition 25 >= 18 would be true. The if block would execute, printing "You are eligible to vote." The else block would be completely ignored.

This is a critical point: With an if-else statement, exactly one block of code—either the if body or the else body—will always run. Never both, and never neither.

This ability to change the path of execution is fundamental. if and if-else statements are what allow our programs to react differently to different inputs and situations, moving them from simple calculators to dynamic, intelligent applications.

Tracing the one-way `if` statement with `cartTotal = 82.50`.
Tracing the one-way `if` statement with `cartTotal = 50.00`.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a couple of examples to solidify this. The key is to think like the computer, evaluating the Boolean condition first.

    Example 1

    Applying a Movie Ticket Discount

    Problem: A movie theater in Boston offers a discount for matinee showings before 5 PM. The standard ticket price is $15. If the movie time is before 5 PM (represented as 17:00 in 24-hour time), the price is reduced to $11. Write a program that calculates the final ticket price for a movie at 2 PM (14:00).

    Step-by-Step Solution:

    1. 1
      Identify the variables
      We need a variable for the standard price and another for the movie time.
      double ticketPrice = 15.00;
      int movieTime = 14; // Using 24-hour format, so 2 PM is 14
    2. 2
      Determine the condition
      The discount applies if the time is before 5 PM (17:00). So, our Boolean expression is movieTime < 17.
    3. 3

      Structure the if statement. This is a one-way if. If the condition is met, we change the price. If not, the price just stays at its default value.

      if (movieTime < 17) {
        // This is the "matinee discount" block
        ticketPrice = 11.00;
        System.out.println("Applying matinee discount...");
      }
    4. 4
      Trace the code
      • The program checks if (14 < 17).
      • This condition is true.
      • Therefore, the code inside the if block executes. ticketPrice is updated from 15.00 to 11.00, and the message is printed.
    5. 5
      Show the final result
      System.out.println("Final ticket price: $" + ticketPrice);
      // Output will be:
      // Applying matinee discount...
      // Final ticket price: $11.0

    Where students go wrong: A common mistake is to try to do the calculation in the condition, like if (ticketPrice = 11.00). Remember, the condition is the question you're asking (is the time before 5 PM?), and the block is the action you take (change the price).

    Equality (`==`) vs. Assignment (`=`) in `if` conditions.

    Example 2

    Checking a Password

    Problem: Write a program that checks if a user-entered password is correct. The correct password is "GoHuskies!24". If it's correct, print "Access Granted". If it's incorrect, print "Access Denied".

    Step-by-Step Solution:

    1. 1
      Set up the variables
      We need one for the correct password and one for what the user typed. We'll use String variables.
      String correctPassword = "GoHuskies!24";
      String userInput = "gohuskies!24"; // Note the lowercase 'g'
    2. 2
      Determine the condition
      We need to check if the userInput is exactly equal to the correctPassword. This is where most students slip up with Strings! You cannot use == to compare the content of Strings. You must use the .equals() method.
      • Wrong
        if (userInput == correctPassword)
      • Correct
        if (userInput.equals(correctPassword))
    3. 3

      Structure the if-else statement. We have two distinct outcomes: access granted or access denied. This is a perfect fit for a two-way if-else.

      if (userInput.equals(correctPassword)) {
        // True path: Passwords match
        System.out.println("Access Granted");
      } else {
        // False path: Passwords do not match
        System.out.println("Access Denied");
      }
    4. 4
      Trace the code
      • The program calls the .equals() method: userInput.equals(correctPassword).
      • It compares "gohuskies!24" to "GoHuskies!24". Because of the different capitalization, these Strings are not equal. The method returns false.
      • Since the condition is false, the if block is skipped, and the else block is executed.
      • The output will be: Access Denied.

    This example highlights not just the if-else structure but also a crucial detail about comparing Strings, which is a very common scenario for conditional logic.

    Try it yourself

    Time to try it on your own. Don't worry about getting it perfect on the first try; focus on setting up the logic.

    1. 1
      Even or Odd?
      Write a program that takes an integer variable, let's call it number, and determines if it is even or odd. Print "The number is even." or "The number is odd." accordingly.
    2. 2
      Amusement Park Ride
      An amusement park ride in Chicago has a height requirement: you must be at least 48 inches tall to ride. Write a program that checks a heightInInches variable. If the person is tall enough, print "You can ride the roller coaster!" Otherwise, print "Sorry, you are not tall enough to ride."
    Flowchart for determining if a number is even or odd.
    Flowchart for amusement park ride height check.