Skip to content
C

Nested if

A nested if is an if statement placed inside another if (or else) block. It's used when a decision only makes sense after another condition has already been satisfied.


1. What is a Nested if?

A nested if is an if statement placed inside another if (or else) block. It's used when a decision only makes sense after another condition has already been satisfied.

2. Why is it used?

Some decisions genuinely depend on multiple layers of conditions — like first checking if a user is logged in, and only then checking if they have admin access. Nested if handles this layered logic.

3. Real-Life Example

Think of entry rules at a club: "If you are 18 or older, then check if you have a valid ID. If both are true, you're allowed in." The ID check only matters once the age condition is already satisfied.

4. Syntax

java
if (condition1) { if (condition2) { // runs only if both condition1 and condition2 are true } }

5. Example Program

java
public class NestedIfDemo { public static void main(String[] args) { int age = 20; boolean hasID = true; if (age >= 18) { if (hasID) { System.out.println("Entry allowed"); } else { System.out.println("ID required"); } } else { System.out.println("Not old enough"); } } }

Output:

Entry allowed

6. Key Points to Remember

  • Nested if is useful when a condition is only relevant after another condition passes.
  • Too many nested levels make code hard to read — consider combining conditions with && instead when possible.
  • Proper indentation is important to keep nested blocks readable.