#15 Java control statements part 2


if-else-if Ladder

 if(condition) 
statement; 
else 
if(condition) 
statement; 
else ]
if(condition)
 statement; ... 

else statement;

The conditional expressions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed, and the rest of the ladder is bypassed. If none of the conditions is true, the final else statement will be executed. The final else often acts as a default condition; that is, if all other conditional tests fail, the last else statement is performed. If there is no final else and all other conditions are false, no action will take place.

// Demonstrate an if-else-if ladder. 

class Ladder {
 public static void main(String args[]) {
 int x; 
for(x=0; x<6; x++) 
{
 if(x==1) 
System.out.println("x is one"); 
else 
if(x==2) 
System.out.println("x is two");
else if(x==3) 
System.out.println("x is three");
 else if(x==4) 
System.out.println
("x is four"); 
else 
System.out.println("x is not between 1 and 4"); 
       } 
    } 
}

The program produces the following output:


x is not between 1 and 4
 x is one 
x is two 
x is three 
x is four 
x is not between 1 and 4

Comments

Popular Posts