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

Nested if Statements

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, nested if statements are about making decisions inside of other decisions, like choosing a meal option only after you've picked a restaurant.

Why this matters

Imagine you're at the DMV, trying to get your first driver's license. There isn't just one question they ask. It's a series of checks. First, the clerk, let's call her Priya, asks for your birth certificate. "Are you 16 or older?" If the answer is no, the conversation ends right there. But if it's yes, you've unlocked the next step.

Priya then asks, "Have you passed the written knowledge test?" If yes, great! You move to the final check: the road test. Only if you pass all three—age, written test, AND road test—do you get your license.

This multi-step, dependent process is exactly what nested if statements are for in programming. One check must pass before the next one is even considered. We're going to break down how to build this powerful logic in Java, so your programs can handle complex, real-world rules just like the DMV.

Concept overview

flowchart TD
    A[Start] --> B{Age >= 16?};
    B -->|No| C[Wait until you are older];
    B -->|Yes| D{Passed Written Test?};
    D -->|No| E[Study and retake test];
    D -->|Yes| F{Passed Road Test?};
    F -->|No| G[Practice and retake test];
    F -->|Yes| H[Issue Driver's License];
    C --> I[End];
    E --> I;
    G --> I;
    H --> I;
This diagram shows a flowchart for the process of getting a driver's license. The process starts and first checks if age is 16 or greater. If no, the process ends. If yes, it then checks if the written test has been passed. If no, the process ends. If yes, it finally checks if the road test has been passed, which then leads to either getting a license or the process ending.

Core explanation

Hello there! I'm Saavi, and I'm excited to walk you through one of the most powerful tools in your programming toolkit: nested if statements. Once you master these, you can write code that handles truly interesting and complex scenarios.

What is a Nested if Statement?

At its heart, a nested if statement is simply an if statement placed inside another if statement.

Think of it like a set of Russian nesting dolls. You have to open the largest doll to find the next one inside. You can't get to the inner doll without first opening the outer one.

In code, the outer if statement acts as a gatekeeper. Its condition must be true for the code inside it—including the inner if statement—to even run.

(EK 2.4.A.2) The Boolean expression of the inner if is only evaluated if the Boolean expression of the outer if evaluates to true.

Let's look at a simple example based on a school club application. To join the robotics club, you must be a full-time student and have a GPA of at least 3.0.

boolean isFullTimeStudent = true;
double gpa = 3.5;

if (isFullTimeStudent == true) {
    System.out.println("First check passed: You are a full-time student.");

    // This is the nested if statement
    if (gpa >= 3.0) {
        System.out.println("Welcome to the Robotics Club!");
    }
}

Here, the program first checks isFullTimeStudent. Since it's true, it executes the code inside the first set of curly braces {}. That includes printing the first message and then evaluating the inner if statement, gpa >= 3.0. Since 3.5 is greater than 3.0, that's also true, and the welcome message is printed.

What if the GPA was 2.8? The outer if would still be true, but the inner if would be false, and the "Welcome" message would never print.

What if isFullTimeStudent was false? The entire block of code for the outer if, including the nested if, would be skipped. The program would jump right past it.

Adding else to the Mix

Nesting works with all forms of conditionals: if, if-else, and if-else-if. This lets you handle every possible outcome.

(EK 2.4.A.1) Nested if statements can be made of any combination of if, if-else, or if-else-if statements.

Let's improve our club example to give feedback to the user.

boolean isFullTimeStudent = true;
double gpa = 2.8;

if (isFullTimeStudent == true) {
    // Outer condition is met
    if (gpa >= 3.0) {
        System.out.println("Welcome to the Robotics Club!");
    } else { // This 'else' belongs to the INNER if
        System.out.println("Your GPA is below the requirement.");
    }
} else { // This 'else' belongs to the OUTER if
    System.out.println("You must be a full-time student to apply.");
}

In this version, if gpa is 2.8, the user gets a specific message: "Your GPA is below the requirement." If isFullTimeStudent were false, they'd get the message: "You must be a full-time student to apply."

Multiway Selection Inside a Nested Structure

Sometimes, your inner check isn't a simple yes/no. It might be a series of possibilities. This is a perfect time to nest an if-else-if ladder.

(EK 2.4.A.3) A multiway selection (if-else-if) can be nested. It will execute at most one block of code—the one corresponding to the first true condition.

Let's imagine a program for a concert venue in Boston. First, it checks if you have a ticket. If you do, it then checks your ticket type to direct you to your seat.

boolean hasTicket = true;
String ticketType = "Balcony";

if (hasTicket == true) {
    System.out.println("Welcome! Let's find your seat.");

    // Nested if-else-if ladder
    if (ticketType.equals("VIP")) {
        System.out.println("Please proceed to the front row.");
    } else if (ticketType.equals("Orchestra")) {
        System.out.println("Your seats are on the main floor.");
    } else if (ticketType.equals("Balcony")) {
        System.out.println("Please take the stairs to your left.");
    } else {
        System.out.println("Please see an usher for assistance.");
    }

} else {
    System.out.println("You need a ticket to enter.");
}

Here, because hasTicket is true, we enter the main block. The program then works its way down the if-else-if ladder. It checks ticketType against "VIP" (false), then "Orchestra" (false), then "Balcony" (true). It prints the balcony directions and, importantly, stops. It doesn't check the final else. Remember, in an if-else-if chain, only the first true block ever runs.

By nesting these structures, you can create clear, logical paths for your program to follow, no matter how many conditions you need to check.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's solidify these ideas with a few examples. The key is to trace the logic step-by-step, just like the computer does.

    Example 1

    Qualifying for a Travel Soccer Team

    Problem: A youth soccer league in Dallas has two tryout requirements. A player must be between the ages of 12 and 15 (inclusive). If they are in the right age group, they also must have a signed permission slip from a parent. Write code to determine if a player, Carlos, is eligible.

    Solution Walkthrough:

    1. 1
      Identify the conditions
      • Outer condition: Is the player's age between 12 and 15?
      • Inner condition: Is the permission slip signed?
    2. 2
      Set up the variables
      int playerAge = 13;
      boolean hasPermissionSlip = true;
    3. 3
      Write the nested structure
      The age check must happen first. Only if the age is correct do we bother checking for the permission slip.
      // Outer check: Age
      if (playerAge >= 12 && playerAge <= 15) {
          System.out.println("Age check passed.");
      
          // Inner check: Permission Slip
          if (hasPermissionSlip == true) {
              System.out.println("Permission slip is valid. Carlos is eligible for tryouts!");
          } else {
              System.out.println("Eligibility pending: a signed permission slip is required.");
          }
      
      } else {
          System.out.println("Carlos is not in the correct age group for this team.");
      }
    4. 4
      Trace the logic
      • The program first evaluates playerAge >= 12 && playerAge <= 15. Since playerAge is 13, this is true && true, which is true.
      • It enters the outer if block.
      • It then evaluates the inner condition: hasPermissionSlip == true. This is true.
      • It enters the inner if block and prints: "Permission slip is valid. Carlos is eligible for tryouts!"

    Where students go wrong: A common mistake is to try to check everything at once with a single if, like if ((playerAge >= 12 && playerAge <= 15) && hasPermissionSlip == true). While this works for a simple "yes/no" outcome, it doesn't allow you to give specific feedback, like "you're the right age, but you're missing the slip." Nested ifs give you more granular control over your program's responses.

    Example 2

    Calculating a Discount at a Bookstore

    Problem: A bookstore in Seattle offers discounts. If a customer is a loyalty member, they get a special discount based on how much they spend.

    • Spend $50 or more: 20% off
    • Spend less than $50: 10% off Non-members do not get a discount. Write code to calculate the final price for a customer named Maya.

    Solution Walkthrough:

    1. 1
      Identify the conditions
      • Outer condition: Is the customer a loyalty member?
      • Inner condition (a multiway selection): How much are they spending?
    2. 2
      Set up the variables
      boolean isLoyaltyMember = true;
      double purchaseTotal = 65.00;
      double finalPrice = purchaseTotal; // Start with the original price
    3. 3
      Write the nested structure
      if (isLoyaltyMember == true) {
          System.out.println("Thank you for being a loyalty member!");
      
          // Nested if-else for discount tiers
          if (purchaseTotal >= 50.0) {
              finalPrice = purchaseTotal * 0.80; // 20% discount
              System.out.println("Applying 20% discount.");
          } else {
              finalPrice = purchaseTotal * 0.90; // 10% discount
              System.out.println("Applying 10% discount.");
          }
      
      } else {
          System.out.println("Join our loyalty program for future discounts!");
          // No change to finalPrice for non-members
      }
      
      System.out.println("Your final price is: $" + finalPrice);
    4. 4
      Trace the logic
      • isLoyaltyMember is true, so the program enters the outer if block.
      • It prints the "Thank you" message.
      • It then evaluates the inner condition purchaseTotal >= 50.0. Since 65.00 is greater than 50.0, this is true.
      • The code calculates finalPrice = 65.00 * 0.80, which is 52.0.
      • The else part of the inner if-else is skipped.
      • The program exits the outer if block and prints the final price: "$52.0".

    This example shows how a nested if-else can be used to apply different rules based on a primary condition being met.

    Try it yourself

    Ready to try on your own? Think through the logic first, then sketch out the code.

    Problem 1: Amusement Park Ride

    An amusement park in Atlanta has a new roller coaster, "The Python." To ride, a person must be at least 54 inches tall. However, if they are also under 16 years old, they must be accompanied by an adult. Write a Java program that takes a riderHeight (in inches) and a riderAge and prints one of three messages:

    1. "Welcome to The Python! Enjoy the ride." (for those who meet all criteria to ride alone)
    2. "You must be accompanied by an adult to ride."
    3. "Sorry, you do not meet the height requirement to ride."

    Problem 2: Code Tracing

    What is the output of the following code snippet? Trace the values of x, y, and z carefully.

    int x = 10;
    int y = 10;
    String z = "start";
    
    if (x >= 10) {
        z = z + "A";
        if (y > 10) {
            z = z + "B";
        } else if (y == 10) {
            z = z + "C";
        }
    } else {
        z = z + "D";
        if (y < 10) {
            z = z + "E";
        }
    }
    System.out.println(z);