The if-else-if Ladder
The if-else-if ladder allows you to check multiple conditions one by one. It is used when you want to execute only one block of code from many possible options based on which condition is true.
How it works:
- The program checks each condition from top to bottom.
- As soon as one condition is true, its block is executed, and the rest are skipped.
- If none of the if or else if conditions are true, the else block runs (if present).
Syntax:
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition2 is true
} else if (condition3) {
// runs if condition3 is true
} else {
// runs if none of the above are true
}
Example:
class ShikshaSanchar {
public static void main(String[] args) {
int marks = 72;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 60) {
System.out.println("Grade: C");
} else if (marks >= 50) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F (Fail)");
}
System.out.println("Hello from outside!");
}
}
Output:
Grade: C
Hello from outside!
Explanation:
- The variable marks is assigned a value of 72.
- The program enters the if-else-if ladder and checks conditions from top to bottom:
- marks >= 90 → false → skip
- marks >= 75 → false → skip
- marks >= 60 → true → this block runs, printing "Grade: C"
- Once a true condition is found and its block is executed, all remaining conditions are skipped.
- After the ladder, "Hello from outside!" is printed — this line runs regardless of which block was executed.
Flow diagram of above program:
Algorithm:
- Program starts and initializes the variable: marks = 72.
- It checks each condition from top to bottom using the if-else-if ladder:
- First: marks >= 90 → false
- Then: marks >= 75 → false
- Then: marks >= 60 → true → so it prints Grade: C
- Since a true condition has been found, Java skips the remaining conditions (marks >= 50, and the else block).
- After the ladder, the final statement ("Hello from outside!") always runs.
- Program ends.
Important Points:
- Use if-else-if when you have 3 or more conditions to check.
- Only one block is executed, even if multiple conditions are true.
- The order of conditions matters — Java checks from top to bottom.
- The final else block is optional, but recommended to handle unmatched cases.
Summary:
The if-else-if ladder is used when you need to check multiple conditions and execute only one matching block.
- The program evaluates each condition from top to bottom.
- As soon as one condition is true, its block is executed.
- Remaining conditions are skipped, even if they are also true.
- If none of the conditions are true, the final else block (if present) is executed.