Nested if Statements: Multi-Level Decisions
What you'll learn: How to place if statements inside other if blocks to handle complex, multi-level decision-making.
The Core Idea
Sometimes a single if-else ladder isn't enough. You might need to check a second (or third) condition only after a first condition is true. Nested if statements let you place one if statement inside another, creating a decision tree with multiple levels.
Think of it like a security checkpoint: first, you check if someone has a ticket. If they do, then you check if it's for the correct date. If that's also true, then you verify their ID. Each check only happens if the previous one passed.
Syntax and Structure
if (outerCondition) {
// Code runs only if outerCondition is true
if (innerCondition) {
// Code runs only if BOTH outerCondition AND innerCondition are true
}
}
Example
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
System.out.println("You are an adult.");
if (hasLicense) {
System.out.println("You can rent a car.");
} else {
System.out.println("You need a license to rent a car.");
}
} else {
System.out.println("You must be 18 or older.");
}
In this example, we first check if age >= 18. Only if that's true do we then check hasLicense. The inner if-else only executes when the outer condition passes.
When to Use Nested ifs
Use nesting when:
- The inner condition is only relevant if the outer condition is true
- You're modeling hierarchical decisions
- Conditions have a natural "parent-child" relationship
Key Takeaway: Nested if statements let you build multi-level decision trees by placing one if block inside another, ensuring inner checks only happen when outer conditions are satisfied.