Nested If Statements

Emily Gardner

Nesting is when something resides in something else.

Nested if statements are similar to if-else statements.  They have two or more if statements, one "nesting" inside the other.

They have an if outer body (statement) and an if inner body (statement).   

First evaluates the condition of the outer if statement.  If it is false, the inner if statement will not be run.  If the outer if statement is true, then the inner if statement will be evaluated.  If the inner if statement is evaluated to be true, the body is run (the println() statement).   

Example code:

int num = 3;

if(num > 0)   //outer if condition

{

       if (num<10) //inner if condition  

{                                         

System.out.println("0<number<10");

}

}

Output: 0<number<10

Multiple If Statements

int num =5;

if(num>0)

{

if(num<10)

{

System.out.println("number is between o and 10");

}

if(num>5)

{

System.out.println("number is between o and 5);

}

if(num==5)

{

System.out.println("number is 5");

}

}

Common Errors

if(num>=5); //never put an ; before an open brace

{

}

if(num=5) //never put only one equal sign

{

}