Skip to content
C

else-if

else-if allows you to check multiple conditions one after another, in order, until one of them turns out to be true. It's used when there are more than two possible outcomes.


1. What is else-if?

else-if allows you to check multiple conditions one after another, in order, until one of them turns out to be true. It's used when there are more than two possible outcomes.

2. Why is it used?

Real-world decisions often have more than two possibilities — like grading a student as A, B, C, or D based on different mark ranges. else-if lets you handle all these ranges in one clean structure.

3. Real-Life Example

Think of a grading rule: "If marks are 90 or above, grade is A. Else if marks are 75 or above, grade is B. Else if marks are 60 or above, grade is C. Otherwise, grade is D." Each condition is checked only if the earlier ones failed.

4. Syntax

java
if (condition1) { // runs if condition1 is true } else if (condition2) { // runs if condition1 is false and condition2 is true } else { // runs if none of the above are true }

5. Example Program

java
public class ElseIfDemo { public static void main(String[] args) { int marks = 78; 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 { System.out.println("Grade D"); } } }

Output:

Grade B

6. Key Points to Remember

  • Conditions are checked top to bottom, and only the first true condition's block runs.
  • Once a matching condition is found, the remaining else if checks are skipped entirely.
  • The final else (if present) acts as a catch-all for anything not matched above.