Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to demonstrate nested if … else if .. statement?

The Java if-else-if statement, often called the if-else-if ladder, chains several conditions together so a program can choose one outcome from many. Java evaluates the conditions from top to bottom, runs the block belonging to the first condition that is true, and skips everything else. An optional final else acts as the catch-all default when none of the conditions hold. For testing a single value against a set of fixed constants you can swap the ladder for a switch, and for a one-line value choice you can use the ternary operator.

The if-else-if Ladder Syntax

The ladder strings together one if, any number of else if branches, and an optional else. Each condition is a boolean expression evaluated in order.

if (condition1) {
    // runs if condition1 is true
} else if (condition2) {
    // runs if condition1 is false and condition2 is true
} else if (condition3) {
    // runs if condition1 and condition2 are false and condition3 is true
} else {
    // runs if every condition above is false
}

How the Ladder Executes

  • Top to bottom: Java checks condition1 first, then condition2, and so on, in the exact order they appear.
  • First match wins: the moment a condition evaluates to true, its block runs and the rest of the ladder is skipped entirely.
  • Single branch: at most one block ever executes, so the branches are mutually exclusive by design.
  • Default fallback: if no condition is true and an else is present, the else block runs; without an else, nothing runs.
  • Order matters: a broad condition placed early can shadow a more specific one below it, leaving that branch unreachable.

Simple if and if-else

A plain if runs a block only when its condition is true. Add an else and you get a two-way decision: one block for true, another for false.

int age = 20;

// simple if
if (age >= 18) {
    System.out.println("You can vote.");
}

// if-else
if (age >= 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}

When you need more than two outcomes, those else branches grow into the if-else-if ladder shown next.

if-else-if-else Chain: A Grade Classifier

A classic use of the ladder is mapping a numeric score to a letter grade. Each else if covers one range, and the final else handles anything outside the expected band.

public class GradeClassifier {
    public static void main(String[] args) {
        int score = 65;

        if (score < 0 || score > 100) {
            System.out.println("Invalid score");
        } else if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else if (score >= 70) {
            System.out.println("Grade: C");
        } else if (score >= 60) {
            System.out.println("Grade: D");
        } else {
            System.out.println("Grade: F");
        }
    }
}

With score set to 65, the first three conditions are false. The branch score >= 60 is the first true one, so the program prints:

Grade: D

Notice that ordering the checks from highest to lowest lets each branch test only its lower bound, since every higher range has already been ruled out above.

Nested if Statements

A nested if places one if inside another, so the inner condition is only checked after the outer one passes. The program below first classifies a number as positive, negative, or zero, then, only for non-zero numbers, reports whether it is even or odd.

public class NumberSign {
    public static void main(String[] args) {
        int number = -8;

        if (number > 0) {
            System.out.println("Positive number");
            if (number % 2 == 0) {
                System.out.println("It is even");
            } else {
                System.out.println("It is odd");
            }
        } else if (number < 0) {
            System.out.println("Negative number");
            if (number % 2 == 0) {
                System.out.println("It is even");
            } else {
                System.out.println("It is odd");
            }
        } else {
            System.out.println("The number is zero");
        }
    }
}

With number set to -8, the outer ladder takes the number < 0 branch, and the inner if finds it divisible by 2, producing:

Negative number
It is even

The Ternary Operator as Shorthand

When an if-else only chooses between two values to assign, the ternary operator condition ? valueIfTrue : valueIfFalse expresses the same logic in a single expression. Because it returns a value, you can drop it straight into an assignment or a method call.

public class TernaryDemo {
    public static void main(String[] args) {
        int age = 20;

        // verbose if-else
        String statusA;
        if (age >= 18) {
            statusA = "Adult";
        } else {
            statusA = "Minor";
        }

        // same result with the ternary operator
        String statusB = (age >= 18) ? "Adult" : "Minor";

        System.out.println(statusA);
        System.out.println(statusB);
    }
}

Both variables resolve to the same value, so the output is:

Adult
Adult

Keep the ternary for short, value-producing choices. Once you need multiple branches or statements with side effects, an if-else-if ladder stays far more readable.

When to Use switch Instead of if-else-if

A switch statement is the cleaner choice when you compare one variable against a list of fixed constant values. The example below maps a day number to a name.

public class DayName {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Another day");
        }
    }
}

With day set to 3, control jumps to case 3 and the program prints:

Wednesday

Use the table below to decide which construct fits.

Use if-else-if ladderUse switch
Ranges, such as score >= 70Exact constant values, such as day == 3
Compound boolean logic with && and ||A single variable tested many times
Comparisons across different variablesint, char, String, or enum constants

Common Pitfalls

  • Using = instead of ==: a single equals sign is assignment, not comparison. Writing if (x = 5) assigns 5 to x rather than testing it. Java rejects this for int conditions, but for a boolean it compiles and quietly changes behavior, so always use == to compare.
  • Missing braces: without braces, only the single next statement belongs to the if. Adding a second indented line later runs it unconditionally. Wrap every branch in braces so the body is unambiguous.
  • Dangling else: an else always binds to the nearest unmatched if, not to the one your indentation suggests. When ifs are nested, use braces to attach the else to the intended condition.
  • Comparing Strings with ==: for objects, == checks whether two references point to the same instance, not whether the text matches. Use name.equals("admin") to compare String contents, reserving == for primitives like int, char, and boolean.
  • Overlapping ranges in the wrong order: placing a broad condition before a narrow one makes the narrow branch unreachable. Order checks from most specific to most general so every branch can fire.

Conditional logic like this sits at the core of automated test scripts, where assertions branch on application state. You can run such Java and Selenium suites across thousands of browser and OS combinations using TestMu AI'sSelenium Testing cloud.

Frequently Asked Questions

What is the difference between if-else and if-else-if in Java?

A plain if-else picks between exactly two outcomes from one condition. An if-else-if ladder chains several conditions so you can route to one of many outcomes. The ladder evaluates each condition top to bottom and runs the block of the first true one, skipping the rest.

Does the order of conditions matter in an if-else-if ladder?

Yes. Because the ladder stops at the first true condition, a broad or overlapping condition placed earlier can shadow later ones. Order conditions from most specific to most general so every branch is reachable.

When should I use a switch statement instead of if-else-if?

Use switch when testing one variable against a list of discrete constant values, such as an int code or a String. It is more readable and the compiler can optimize it. Use an if-else-if ladder for ranges, compound boolean logic, or comparisons across different variables.

What does the ternary operator do in Java?

The ternary operator condition ? valueIfTrue : valueIfFalse is a compact expression that returns one of two values. It is shorthand for a small if-else that assigns a value, and it can be used directly inside assignments or method arguments.

Why does == not work for comparing String values in Java?

For String objects, == compares references, that is, whether both variables point to the same object, not the characters. Use the .equals() method to compare String contents. The == operator is only reliable for primitive types like int, char, and boolean.

Can I write an if-else-if ladder without braces?

Java allows a single statement after if without braces, but it is error prone. Only the next single statement is governed by the condition, which causes subtle bugs when you later add a second line. Always use braces for every branch in production code.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests