Java: Nested if statement

In the if statement we can also nest the statements which is a green light for doing that too. That is nesting an if condition inside an else condition etc.

Syntax

if (condition)
{
    //statement
}
else
{
    if()
    {
        //statement
    }
}

Example

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        int age = 60;
        
        if(age < 50)
        {
            System.out.println("You are young");
        }
        else
        {
            System.out.println("You are old");
            if (age > 75)
            {
                System.out.println("you are REALLY old!");
            }
            else
            {
                System. out.println("Don't worry you aren't that old");
            }
        }
    }
}

Output

You are old
Don't worry you aren't that old
  • Here I have nested the if statement inside the second else of the first if statement.
  • As the age variable is not less than 50 it satisfies the outer else statement.
  • Then it checks for the age if it is greater than 75 as it is not greater it satisfies the nested else statement.
Tue, 10/26/2021 - 15:13

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags