Skip to main content

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.
Tags
Submitted by arilio666 on October 26, 2021

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.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.