0
0
Javaprogramming~5 mins

Else–if ladder in Java

Choose your learning style9 modes available
Introduction

An else-if ladder helps you check many conditions one after another. It lets your program choose only one path to follow based on these checks.

When you want to decide between multiple options, like grading scores.
When you need to check ranges of values, such as age groups.
When you want to perform different actions based on user input.
When you want to handle different error types separately.
When you want to pick one choice out of many possibilities.
Syntax
Java
if (condition1) {
    // code to run if condition1 is true
} else if (condition2) {
    // code to run if condition2 is true
} else if (condition3) {
    // code to run if condition3 is true
} else {
    // code to run if none of the above conditions are true
}

The conditions are checked from top to bottom.

Only the first true condition's code runs, then the rest are skipped.

Examples
This checks if a number is positive, negative, or zero and prints the result.
Java
int number = 10;
if (number > 0) {
    System.out.println("Positive number");
} else if (number < 0) {
    System.out.println("Negative number");
} else {
    System.out.println("Zero");
}
This assigns grades based on marks using an else-if ladder.
Java
int marks = 75;
if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else if (marks >= 50) {
    System.out.println("Grade C");
} else {
    System.out.println("Fail");
}
Sample Program

This program checks the temperature and prints a message that matches the temperature range.

Java
public class ElseIfLadderExample {
    public static void main(String[] args) {
        int temperature = 30;
        if (temperature > 40) {
            System.out.println("It's very hot outside.");
        } else if (temperature >= 31) {
            System.out.println("It's hot outside.");
        } else if (temperature > 20) {
            System.out.println("The weather is pleasant.");
        } else if (temperature > 10) {
            System.out.println("It's a bit cold.");
        } else {
            System.out.println("It's cold outside.");
        }
    }
}
OutputSuccess
Important Notes

Make sure conditions do not overlap in a way that causes confusion.

The else block is optional but useful to catch all other cases.

Use else-if ladder for clear multiple condition checks instead of many separate ifs.

Summary

Else-if ladder helps check multiple conditions one by one.

Only the first true condition runs its code.

Use else to handle all other cases not covered by conditions.