Java if-else-if ladder with Example | Definition, Syntax, Flowchart & Example Program of If-Else-If Statement in Java

A programming language utilizes control statements to control the flow of execution of a program. In Java programming, we can control the flow of execution of a program based on some conditions. Java control statements can be put into the following three categories: selection, iteration, and jump. In this tutorial, you will learn completely about the java if-else-if ladder statement with an example.

Java if-else-if ladder Statement

Java if-else-if ladder is applied to work on multiple conditions. The if statements are executed from the top down. When one of the conditions controlling the if and it is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.

If none of the conditions is true, then the final else statement 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.

Syntax of if-else-if:

if(condition1){
//statement1;
}
else if(condition2){
//statement2;
}
else if(condition3){
//statement3;
}
.........
.........
.........
else{
//default statement;
}

Do Check:

How the if…else…if ladder works?

  1. Control falls into the if block.
  2. The flow jumps to Condition 1.
  3. Condition is tested.
    • If Condition yields true, go to Step 4.
    • If Condition yields false, go to Step 5.
  4. The present block is executed. Go to Step 7.
  5. The flow jumps to Condition 2.
    • If Condition yields true, go to step 4.
    • If Condition yields false, go to Step 6.
  6. The flow jumps to Condition 3.
    • If Condition yields true, go to step 4.
    • If Condition yields false, execute else block. Go to Step 7.
  7. Exit the if-else-if ladder.

Look at the following image format of Working of the if-else-if ladder:

Working of the if-else-if ladder image

Flowchart if-else-if ladder:

Java if-else-if ladder with Example 1

Java if-else-if ladder Example:

class IfElseLadder {
public static void main(String[] args) {

int examscore = 75;
char grade;

if(examscore >= 90) {
grade = 'A';
} else if (examscore >= 80) {
grade = 'B';
} else if(examscore >= 70) {
grade = 'C';
} else if(examscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade is = " + grade);
}
}

Output:

Grade is = C