Java-if-else-if-Ladder .

In this session i have discussed if-else-if ladder in Java .


IF-Else-IF-Ladder :

It is also decision making and branching statement . If you have multiple choice then you can use the if-else-if ladder or switch . In if-else-if case first control check the if condition if it is true then the contorl come inside the if body other wise control transfer to else-if statement check the condition if it is true then contorl come inside the else if body and go on . If no any condition match then last else statement become execute .

IF-Elese-IF-statement-syntax :

 image


Example : Write a java program that check the days of week according to given value .

 class Hello{ 
         
      public static void main(String args[]){  
          int i=3;
          if(i==1){
               System.out.println("Sunday");
          }
          else if(i==2){
               System.out.println("Monday");
          }
          else if(i==3){
               System.out.println("Tuesday");
          }
          else if(i==4){
               System.out.println("Wednesday");
          }
          else if(i==5){
               System.out.println("Thursday");
          }
          else if(i==6){
               System.out.println("Friday");
          }
          else if(i==7){
               System.out.println("Sutarday");
          }
          else{
               System.out.println("Invalid Number");
          }  
      }  
 }
    
    OUTPUT : Tuesday
    


Example : Write a program that perform 1-Addition , 2-Subtraction , 3-multiplication , 4 Division .

 class Hello{ 
         
      public static void main(String args[]){  
           int op=2;
           int x=20;
           int y=10;
           if(op==1){
               int sum=x+y;
               System.out.println("Sum : "+sum);
          }
          else if(op==2){
               int sub=x-y;
               System.out.println("Sub : "+sub);
          }
          else if(op==3){
               int mul=x*y;
               System.out.println("Mul : "+mul);
          }
          else if(op==4){
               int div=x/y;
               System.out.println("Div : "+div);
          }
          else{
               System.out.println("Invalid Number");
          }  
      }  
 }
    
    OUTPUT : Sub= 10
    


Welcome to AndroidATPoint.

back image                     next image