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:

  • Implementing a state machine with multiple states and transitions.
  • Handling different types of user requests in a web server.
  • Categorizing data based on multiple criteria.
  • Implementing different levels of discounts based on purchase amount.

Best Practices

When using if-else if-else statements:

  • Arrange the conditions in a logical order (e.g., from most specific to least specific).
  • Ensure that the conditions are mutually exclusive to avoid unexpected behavior.
  • Consider using a switch statement if you are checking equality against multiple constant values.
  • Add a default 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:

  • Switch statement: Ideal for equality checks against a fixed set of values. Often more readable than deeply nested if-else structures when applicable.
  • Decision Table: (Advanced) Can be used to represent complex decision logic in a tabular format, which can then be implemented in code.
  • Chain of Responsibility Pattern: (Advanced) A design pattern that allows you to pass a request along a chain of handlers until one of them handles the request.

FAQ

  • What happens if none of the conditions in the if-else if-else chain are true?

    If none of the conditions are true, the else block (if present) will be executed. If there is no else block, the code execution will continue to the next statement after the if-else if-else chain.
  • Is the else block mandatory in an if-else if-else statement?

    No, the else block is optional. However, it's often a good practice to include an else block to handle unexpected or default cases.
  • Can I have multiple else if blocks?

    Yes, you can have as many else if blocks as needed to handle different conditions.