If-else-If Ladder


In this, the if statement is followed by multiple else-if blocks. We can create a decision tree by using these control statements in Java in which the block where the condition is true is executed and the rest of the ladder is ignored and not executed. If none of the conditions is true, the last else block is executed, if present.

Syntax:

if(condition1) {

    // Executed only when the condition1 is true

}

else if(condition2) {

    // Executed only when the condition2 is true

}

.

.

.

.

else {

    // Executed when all the conditions mentioned above are true

}

Example:

public class IfElseIfLadderConcept {

               public static void main(String[] args) {

                              int marks = 67;

                              if (marks >= 68) {

                                             System.out.println("First Class with Distinction");

                              } else if (marks < 68 && marks >= 60) {

                                             System.out.println("First Class");

                              } else if (marks < 60 && marks >= 55) {

                                             System.out.println("Higher Second Class");

                              } else if (marks < 55 && marks >= 50) {

                                             System.out.println("Secind Class");

                              } else if (marks < 50 && marks >= 40) {

                                             System.out.println("Pass");

                              } else {

                                             System.out.println("Fail");

                              }

               }

}

 

Output: 

First Class