Nested if-else statement

A nested if-else statement means an if-else statement containing another if-else statement. Using nested if-else statements we can control the flow of the program based on multiple levels of conditions.

Syntax

if (<condition 1>) {

    if (<condition 2>) {
        // Code to be executed if condition 1 and 2 both are true
    } else {
        // Code to be executed if condition 1 is true but 2 is false
    }

} else {

    if (<condition 1>) {
        // Code to be executed if condition 1 and 2 both are true
    if (<condition 2>) {
        // Code to be executed if condition 1 is true but 2 is false
    }

}

Example

In this program, we are comparing person A’s age with Person B, C.

import java.util.Scanner;

public class NestedIfElseExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter age for person A : ");
        int ageA = scanner.nextInt();

        System.out.println("Enter age for person B : ");
        int ageB = scanner.nextInt();

        System.out.println("Enter age for person C : ");
        int ageC = scanner.nextInt();

        if (ageA > ageB) {

            if (ageA > ageC) {
                System.out.println("A is older than B and C.");
            } else {
                System.out.println("A is older than B, but younger than C");
            }

        } else {

            if (ageA > ageC) {
                System.out.println("A is younger than B, but older than C.");
            } else {
                System.out.println("A is younger than B and C.");
            }

        }
    }
}

Flow diagram