Monday, October 28, 2013

Flow Control - Nested If

Nested ifs 

A nested if is an if statement that is the target of another if or else, Nested ifs are very common in programming, when You nest ifs, the main thing to remember is the and else statement always refer to the nearest if statement that is withing the same block as the else and that is not already associated with an else.
class NestedIfs {

    public static void main(String[] args) {
        int i = 10;
        int k = 20;
        if (i == 10) {
            int j =10;
            if (j < 20) {
            }
            if(k >20){ // this if is associated with
            }else{//this else
            }
        } else {
            // this else refers to if (i==10)
        }
    }
}
As the comments indicate, the final else is not associated with if (j<20) because it is not in the same block (even though it is the nearest if without an else).Rather, the final else is associated with  if(i==10). the inner else refers to if (k > 20) because it is the closest if within the same block.

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the if else if ladder. It looks like this 
if(condition){
             // Statement;
}else if(condition){
           // Statement;
}else if(condition){
          // Statement;
}.....
...............
...............
...............
..............
else{
            // Statement;
}
The if statements are executed from the top do down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, conditions is true, then the final else statements will be executed, the final else acts as a default condition,That is if all other conditional tests fail, then the last else statement is performed. if there is no final else and all other conditions are false, then no action will take place.The following simple program uses an if else if ladder.
class IfElseIF {

    public static void main(String[] args) {
       int x = 10;
       if(x == 8){
           System.out.println("X is eight");
       }else if(x == 9){
           System.out.println("x is nine");
       }else if(x==10){
           System.out.println("x is ten");
       }else{
           System.out.println("x big then ten");
       }
    }
}

No comments:

Post a Comment