Java Nested if

Last Updated : 13 Jun, 2026

Nested if in Java refers to placing one if statement inside another if statement. It is used when a condition depends on another condition being true before it can be evaluated. This helps in handling multiple related decisions in a structured manner.

  • A nested if contains an if statement inside another if statement.
  • The inner condition is checked only if the outer condition is true.
  • It is useful for evaluating multiple dependent conditions.
first_if
Java Nested if

The above diagram shows that the inner if condition is checked only after the outer if condition evaluates to true. If any condition evaluates to false, the corresponding block is skipped and program control moves to the next statement.

Java
import java.io.*;
import java.lang.*;
import java.util.*;

class Geeks {
    public static void main(String args[])
    {
        int a = 10;
        int b = 20;

        // Outer if condition
        if (a == 10) {
          
            // Inner if condition
            if (b == 20) {
                System.out.println("GeeksforGeeks");
            }
        }
    }
}

Output
GeeksforGeeks

Explaination: In the above example, one if condition is placed inside another. If both conditions are true, it prints GeeksforGeeks

Syntax

if (condition1) {
if (condition2) {
if (condition3) {
// Statements
}
}
}

Note: If the outer condition satisfies then only the inner condition will be checked. Along with if condition, else condition can also be executed.

Example 2: The below Java program demonstrates the use of nested if-else statements to execute multiple conditions and different code block based on weather the inner condition is true or false.

Java
import java.lang.*;
import java.util.*;

class Geeks {
    public static void main(String args[])
    {
        int a = 10;
        int b = 20;
      
        // Outer if condition
        if (a == 10) {

            // Inner if condition
            if (b != 20) {
                System.out.println("GeeksforGeeks");
            }

            else {
                System.out.println("GFG");
            }
        }
    }
}

Output
GFG

Explanation: In the above example, it first checks if a is equal to 10. If the condition satisfies, it then checks the inner condition b != 20. If the inner condition is false, the else block executes, it prints GFG.

Advantages

  • It provides a clear structure for handling multiple related conditions.
  • It ensures that inner conditions are evaluated only when necessary, improving efficiency.

Disadvantages

  • Overuse of this condition can make the code harder to read and maintain.
  • It may lead to increased complexity if not structured properly.
Comment