0
0
Javaprogramming~5 mins

Nested if statements in Java

Choose your learning style9 modes available
Introduction

Nested if statements help you check multiple conditions step by step. They let you make decisions inside other decisions.

When you want to check if a number is positive and then check if it is even or odd.
When you need to verify a password and then check if the user has admin rights.
When you want to decide what to wear based on weather and then based on temperature.
When you want to check if a student passed and then check if they got honors.
When you want to check if a store is open and then check if a product is in stock.
Syntax
Java
if (condition1) {
    if (condition2) {
        // code to run if both conditions are true
    }
}
The second if is inside the first if's block, so it runs only if the first condition is true.
You can have many levels of nested ifs, but keep it simple to avoid confusion.
Examples
This checks if someone is older than 18 and then if they have a license before saying they can drive.
Java
if (age > 18) {
    if (hasLicense) {
        System.out.println("Can drive");
    }
}
This checks if the score is passing, then if it is very high for a special grade.
Java
if (score >= 50) {
    if (score >= 90) {
        System.out.println("Grade A");
    } else {
        System.out.println("Passed");
    }
}
Sample Program

This program checks if a number is positive. If yes, it then checks if it is even or odd and prints the result.

Java
public class NestedIfExample {
    public static void main(String[] args) {
        int number = 12;
        if (number > 0) {
            if (number % 2 == 0) {
                System.out.println("The number is positive and even.");
            } else {
                System.out.println("The number is positive and odd.");
            }
        } else {
            System.out.println("The number is not positive.");
        }
    }
}
OutputSuccess
Important Notes

Nested ifs help organize checks that depend on earlier checks.

Too many nested ifs can make code hard to read, so use them carefully.

Summary

Nested if statements let you check one condition inside another.

They are useful for step-by-step decision making.

Keep nesting simple to keep your code clear.