Java > Core Java > Control Flow > If-Else Statements
If-Else If-Else: Grading System Example
This example demonstrates the use of if-else if-else statements to implement a simple grading system. Based on a student's score, a corresponding grade is assigned and printed.
Code Snippet
The code defines a class `GradingSystem` with a `main` method. Inside `main`, an integer variable `score` is initialized with a student's score. The if-else if-else chain checks the score against different grade ranges. The first if condition checks if the score is greater than or equal to 90. If it is, the grade is assigned 'A'. If not, the next else if condition checks if the score is greater than or equal to 80, and so on. If none of the if or else if conditions are met, the else block is executed, assigning the grade 'F'.
public class GradingSystem {
public static void main(String[] args) {
int score = 85; // You can change this score to test different grade ranges
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Score: " + score);
System.out.println("Grade: " + grade);
}
}
Concepts Behind the Snippet
The if-else if-else statement extends the basic if-else construct to handle multiple conditions. It allows you to chain together multiple if conditions, where each condition is checked only if the preceding conditions are false. The else block is executed only if none of the preceding conditions are true.
Real-Life Use Case
Examples of if-else if-else statements in real-world applications:
Best Practices
When using if-else if-else statements:
switch statement if you are checking equality against multiple constant values.else block to handle unexpected or edge cases.
Interview Tip
Be able to explain the order of evaluation in an if-else if-else chain. Understand the importance of mutually exclusive conditions. Be prepared to discuss the trade-offs between using if-else if-else and switch statements.
When to use them
Use if-else if-else statements when you have multiple conditions that need to be checked sequentially. It's particularly useful when the conditions are related to each other and represent different ranges or categories.
Alternatives
Alternatives to if-else if-else statements include:
if-else structures when applicable.
FAQ
-
What happens if none of the conditions in the
if-else if-elsechain aretrue?
If none of the conditions aretrue, theelseblock (if present) will be executed. If there is noelseblock, the code execution will continue to the next statement after theif-else if-elsechain. -
Is the
elseblock mandatory in anif-else if-elsestatement?
No, theelseblock is optional. However, it's often a good practice to include anelseblock to handle unexpected or default cases. -
Can I have multiple
else ifblocks?
Yes, you can have as manyelse ifblocks as needed to handle different conditions.