Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Nested if statement

In Java programming, it is possible to place if control statement inside another if-block or else-block.

Basic structure

if(condition1)   // outer if-block
{
    if(condition2)
    {
        block1
    }
}
else      // outer else-block
{
    if(condition3)
    {
        block2
    }
}

In the above example, if condition1 becomes true, program control enters into outer if-block. Then it checks for condition2. If condition2 is true, block1 is executed.
After execution of block1, control is transferred directly to the statement after the outer else-block.
If condition1 becomes false, program control enters into outer else-block skipping outer if-block. Then it checks for condition3. If condition3 is true, block2 is executed. After execution of block2 and outer else-block control is transferred directly to statement after it.

Java – Nested if-else statement

In Java programming, it is possible to place if-else control statement inside another if-block or else-block.

It works similar to the nested if statement.

Basic structure

if(condition1)
{
    if(condition2)
    {
        block1
    }
    else
    {
        block2
    }
}
else
{


}

Example

class NestedIfElse 
{
    public static void main(String args[])
    {
        int david,john,andrew;
        david = 19;
        john = 24;
        andrew = 21;
	    
        if(david>john)
        {
            if(david>andrew)
            {
                System.out.println("david is older than john & andrew");
            }
            else
            {
                System.out.println("Andrew is older than david & john");
            }
        }
        else
        {
            if(john>andrew)
            {
                System.out.println("\n john is older than david & andrew");
            }
            else
            {
                System.out.println("\n Andrew is older than david & john ");
            }
        }	
    }
}

Output

john is older than david & andrew

 

Leave a reply