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 Statement

Java's if-else statement executes one block of code when a condition is true and a different block when it is false. A nested if-else places one if-else inside another, letting you test multiple dependent conditions in sequence — for example, deciding the largest of three numbers or assigning a letter grade. These are part of Java's conditional (decision-making) statements, which control program flow based on Boolean expressions.

Below, we walk through every form of the if statement in Java, then build the headline example — a complete, runnable nested if…else program — followed by more examples, comparisons, best practices, and the mistakes that trip up most beginners.

What Is the if-else Statement in Java

The if-else statement is one of Java's core conditional (decision-making) statements. It evaluates a Boolean expression — an expression that resolves to either true or false — and runs one of two blocks of code accordingly. If the condition is true, the if block runs; otherwise the else block runs. This is how a Java program chooses different paths at runtime instead of executing every line top to bottom.

The basic syntax looks like this:

if (condition) {
    // runs when condition is true
} else {
    // runs when condition is false
}

The condition must evaluate to a boolean. Unlike some languages, Java does not treat numbers or non-null objects as "truthy" — if (1) is a compile error. You must write an explicit comparison such as num > 0 or a boolean variable. This strictness prevents a whole class of bugs.

Types of if Statements in Java

Java provides four practical forms of the if construct. Knowing which one fits your problem keeps logic readable.

1. Simple if statement

Runs a block only when the condition is true; otherwise nothing happens.

if (age >= 18) {
    System.out.println("You are eligible to vote.");
}

2. if-else statement

Provides an alternative path when the condition is false.

if (age >= 18) {
    System.out.println("Eligible to vote.");
} else {
    System.out.println("Not eligible yet.");
}

3. if-else-if ladder

Tests a series of conditions in order and runs the first true block, falling through to a final else if none match. For a dedicated walkthrough of this form, see the nested if-else-if statement program.

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("Fail");
}

4. Nested if-else

Places one if-else inside another. The inner condition is evaluated only when the outer condition is true, which is exactly what you need for dependent decisions. This also makes it efficient — an inner check that is irrelevant when the outer condition fails is simply never run, so you avoid needless comparisons (for example, checking donation weight only after confirming the donor meets the minimum age).

if (outerCondition) {
    if (innerCondition) {
        // runs when both are true
    } else {
        // runs when outer is true but inner is false
    }
} else {
    // runs when outer is false
}

Nested if…else Program Example

Here is the headline ask: a complete, runnable Java program that uses a nested if…else to find the largest of three numbers. The inner if-else runs only after the outer condition has narrowed the candidates, which perfectly demonstrates dependent conditions.

public class LargestOfThree {
    public static void main(String[] args) {
        int a = 25, b = 42, c = 17;
        int largest;

        if (a > b) {
            // a is bigger than b, now compare a with c
            if (a > c) {
                largest = a;
            } else {
                largest = c;
            }
        } else {
            // b is bigger than or equal to a, now compare b with c
            if (b > c) {
                largest = b;
            } else {
                largest = c;
            }
        }

        System.out.println("The largest number is: " + largest);
    }
}

For the values above, the output is:

The largest number is: 42

Notice how the inner if (a > c) is only reached when the outer if (a > b) is already true. That dependency is the defining trait of a nested if-else. The same pattern scales to grade classification, where you first check the broad band, then refine inside it:

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

        if (score >= 60) {
            // student passed, now decide the grade band
            if (score >= 90) {
                System.out.println("Pass - Grade A");
            } else if (score >= 75) {
                System.out.println("Pass - Grade B");
            } else {
                System.out.println("Pass - Grade C");
            }
        } else {
            System.out.println("Fail - Please reattempt");
        }
    }
}

Here the grade band is only evaluated after we confirm the student passed — a natural, real-world nesting of decisions.

More Examples - Even/Odd and Eligibility

Two classic beginner programs show the simple if-else in action. First, checking whether a number is even or odd using the modulo operator:

public class EvenOdd {
    public static void main(String[] args) {
        int num = 12;
        if (num % 2 == 0) {
            System.out.println(num + " is an Even Number");
        } else {
            System.out.println(num + " is an Odd Number");
        }
    }
}

Next, a nested eligibility check that confirms a person is both old enough and a citizen before allowing them to vote — two conditions where the second only matters if the first passes:

public class VotingEligibility {
    public static void main(String[] args) {
        int age = 20;
        boolean isCitizen = true;

        if (age >= 18) {
            if (isCitizen) {
                System.out.println("You can vote.");
            } else {
                System.out.println("Citizenship required to vote.");
            }
        } else {
            System.out.println("You must be at least 18 to vote.");
        }
    }
}

if-else-if Ladder vs switch

When you have many discrete options, a switch statement is often cleaner than a long if-else-if ladder. The table below compares the two so you pick the right tool.

  • Condition type: if-else-if ladder handles any boolean expression, including ranges; switch handles equality only (int, char, String, enum).
  • Best for: if-else-if ladder suits ranges and complex logic (marks >= 90); switch suits a fixed set of exact values (menu choices).
  • Readability with many cases: an if-else-if ladder becomes long and repetitive; a switch stays compact and easy to scan.
  • Fall-through: not applicable to an if-else-if ladder; a switch requires break to avoid fall-through.

In short: use a ladder when conditions are ranges or involve multiple variables; use a switch when you are matching one variable against a fixed list of exact values.

Ternary Operator Shorthand

When an if-else simply assigns or returns a value, the ternary operator condenses it into a single expression: condition ? valueIfTrue : valueIfFalse.

int num = 7;

// Full if-else
String result;
if (num % 2 == 0) {
    result = "Even";
} else {
    result = "Odd";
}

// Equivalent ternary shorthand
String shorthand = (num % 2 == 0) ? "Even" : "Odd";

System.out.println(shorthand); // Odd

Ternaries are great for short assignments, but avoid nesting them deeply — a chain of nested ternaries is far harder to read than an equivalent if-else-if ladder.

Best Practices

  • Always use braces — even for single-statement blocks. It prevents bugs when you later add a second line.
  • Limit nesting depth — more than two or three levels signals you should extract a method or use guard clauses (early returns).
  • Handle the else — provide a final else or default so unexpected input never falls through silently.
  • Order conditions sensibly — in an if-else-if ladder, put the most likely or most specific condition first.
  • Prefer .equals() for objects — never compare Strings or wrapper objects with == inside conditions.

Common Mistakes

  • Using = instead of ==if (x = 5) assigns rather than compares. For booleans it compiles and is always true; for ints it is a compile error. Always use == for comparison.
  • Missing braces — without braces, only the first statement belongs to the if. A second indented line runs unconditionally, a classic source of silent bugs.
  • Dangling else — in nested code an else binds to the nearest unmatched if, not the one you visually intended. Braces remove the ambiguity.
  • Comparing Strings with ==name == "admin" compares references, not text. Use name.equals("admin") or equalsIgnoreCase() instead.
  • Forgetting the boolean type — Java conditions must be boolean. Writing if (count) where count is an int will not compile; write if (count > 0).
String name = "admin";

// Wrong: compares references, can be false
if (name == "admin") { /* unreliable */ }

// Correct: compares the text content
if (name.equals("admin")) {
    System.out.println("Welcome, admin!");
}

Conclusion

Java's if-else is the foundation of decision-making: it runs one block when a condition is true and another when false. A nested if-else extends that by testing an inner condition only after an outer one passes — perfect for problems like the largest of three numbers or grade classification shown above. Choose a ladder for flat independent choices, a switch for fixed value sets, and the ternary for short value assignments. Add braces, mind the = vs == trap, and compare Strings with .equals(), and your conditional logic will stay clear and bug-free.

Frequently Asked Questions

What is a nested if-else statement in Java?

A nested if-else is an if-else placed inside the if or else block of another if-else. It evaluates a second condition only after the first has been resolved, making it ideal for dependent decisions such as finding the largest of three numbers or assigning a grade band.

What is the difference between an if-else-if ladder and a nested if-else?

An if-else-if ladder checks a sequence of independent conditions and stops at the first true one. A nested if-else evaluates an inner condition only when the outer condition is already true, so it models dependent decisions rather than a flat list of choices.

Can I replace a simple if-else with the ternary operator?

Yes. The ternary operator (condition ? valueIfTrue : valueIfFalse) is a one-line shorthand for an if-else that returns a value. Use it for short assignments. For multiple statements or deeply nested logic, a full if-else block stays more readable.

Why does my Java if condition always evaluate to true?

You likely used the assignment operator = instead of the comparison operator ==. With a boolean variable, if(flag = true) compiles and is always true. Always use == for primitives, or .equals() for objects, inside conditions to compare rather than assign.

How do I compare two Strings inside a Java if statement?

Use the .equals() method, such as if(name.equals("admin")), not ==. The == operator compares object references, so two String objects with the same text can return false. Use .equalsIgnoreCase() when you want a case-insensitive match.

What is the syntax of a nested if statement in Java?

A nested if places one if (or if-else) inside another: if (outer) { if (inner) { /* both true */ } }. The inner block only runs when the outer condition is true. Always wrap each level in braces so the compiler and the reader agree on which else pairs with which if.

How many levels can if-else be nested in Java?

Java sets no hard limit on nesting depth, so you can nest as deeply as needed. In practice, keep it to two or three levels — beyond that, readability drops fast. Refactor deeper logic into separate methods, guard clauses (early returns), or a switch to keep the code maintainable.

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