Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Java If-else Statement

The if-else statement is Java's basic decision-making construct: it lets a program execute one block of code or another based on whether a boolean condition is true or false. Almost every non-trivial program branches somewhere, and if-else is the tool that makes that branching explicit and readable.

Java evaluates the condition inside the parentheses, and that condition must be a boolean expression — unlike C, Java does not allow an int to be used directly as a condition. This strictness catches a whole class of bugs (like accidentally writing if (x = 5) instead of if (x == 5)) at compile time rather than letting them silently misbehave at runtime.

Why it matters

Almost every business rule ends up as a condition: who gets a discount, which requests are allowed, what happens when a value is missing. The mistakes here are rarely syntax errors — they are conditions tested in the wrong order or an else attached to a different if than the indentation suggests — so the code runs and quietly gives the wrong answer.

The if, if-else, and if-else-if Forms

Java supports three shapes of this statement, each suited to a different kind of decision.

  • if — runs a block only when the condition is true; otherwise nothing happens.
  • if-else — runs one block when the condition is true and a different block when it is false; exactly one branch always executes.
  • if-else-if ladder — chains multiple conditions checked top to bottom; the first true condition wins, and only its block runs even if a later condition would also be true.

Watch: How the Dangling Else Breaks Code

A quick video on the dangling else problem — which if an else really belongs to, and how braces fix it.

Watch on YouTube

Nested if and Braces

An if statement can contain another if statement inside its block, which is useful when a second decision only makes sense after the first condition is satisfied. Java allows you to omit curly braces when a branch is a single statement, but doing so is risky: only the very next statement belongs to the if, and any developer who later adds a second statement without adding braces will silently break the logic. Professional style always uses braces, even for one-line branches.

The Dangling else Problem

When if statements are nested without braces, an else always binds to the nearest unmatched if, not necessarily the one the indentation visually suggests. This is called the "dangling else" ambiguity, and it is a real source of bugs when code is reformatted or edited. Using braces around every branch removes the ambiguity entirely, because the else then has only one possible if to attach to.

Example

An if-else-if ladder assigning a letter grade from a numeric score

Java
public class GradeChecker {
    public static void main(String[] args) {
        int score = 82;
        char grade;

        if (score >= 90) {
            grade = 'A';
        } else if (score >= 80) {
            grade = 'B';
        } else if (score >= 70) {
            grade = 'C';
        } else {
            grade = 'F';
        }

        System.out.println("Grade: " + grade);
    }
}
Output
Grade: B

Common Mistakes

  • Writing "if (x = 5)" instead of "if (x == 5)" — Java prevents this specific mistake at compile time because assignment does not produce a boolean, but it still confuses beginners coming from other languages.
  • Omitting braces on a single-statement branch and later adding a second statement that unintentionally falls outside the if.
  • Ordering an if-else-if ladder incorrectly, such as checking "score >= 70" before "score >= 90" — the first matching branch wins, so broader conditions must come last.
  • Comparing objects like String with == instead of .equals() inside an if condition, which compares references rather than content.

Exercise

Write the ticket-price rule for a museum: children under 5 enter free, ages 5 to 17 pay 100, ages 18 to 59 pay 200, and anyone 60 or older pays 120.

Expected output: 0, 100, 200, 120, each on its own line.

Java · starter code
public class TicketPrice {

    static int priceFor(int age) {
        // TODO: return the price for this age
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(priceFor(3));
        System.out.println(priceFor(12));
        System.out.println(priceFor(30));
        System.out.println(priceFor(65));
    }
}
Show hints
  • Test the ranges in order, from the youngest upward, so each condition only needs one comparison.
  • The last range needs no condition at all: it is the final else.
Show solution
Java · solution
public class TicketPrice {

    static int priceFor(int age) {
        if (age < 5) {
            return 0;
        } else if (age < 18) {
            return 100;
        } else if (age < 60) {
            return 200;
        } else {
            return 120;
        }
    }

    public static void main(String[] args) {
        System.out.println(priceFor(3));
        System.out.println(priceFor(12));
        System.out.println(priceFor(30));
        System.out.println(priceFor(65));
    }
}

Quick quiz

1. With int x = 5;, what does if (x > 3) if (x > 10) System.out.print("A"); else System.out.print("B"); print?

  • A. B
  • B. A
  • C. Nothing
  • D. It does not compile
Show answer

A. An else always belongs to the nearest unmatched if, which is the inner one. x > 3 is true, x > 10 is false, so the else runs and prints B.

2. With int x = 3;, what happens with if (x = 5) { ... }?

  • A. The block runs
  • B. The block is skipped
  • C. It throws an exception
  • D. It does not compile
Show answer

D. x = 5 is an assignment whose value is an int. An if condition must be a boolean, so the compiler rejects it.

3. A ladder tests score >= 60 first (grade D) and then score >= 90 (grade A). What grade does a score of 95 get?

  • A. D
  • B. A
  • C. Both
  • D. Neither
Show answer

A. Only the first true branch of an if-else-if ladder runs. 95 >= 60 is true, so the A branch is never reached. Test the most specific condition first.

Interview questions

What is the dangling else problem?

Show answer

When if statements are nested without braces, it can look as though an else belongs to the outer if when the compiler actually pairs it with the nearest unmatched inner if. Indentation has no effect on this. The fix is to always use braces, which makes the pairing explicit.

When would you use the ternary operator instead of if-else?

Show answer

When you are choosing between two values, not two actions. String label = count == 1 ? "item" : "items"; is clearer than a four-line if-else. For anything with side effects, several statements, or more than one level of nesting, a normal if-else is easier to read and debug.

Key Points to Remember

  • The condition in an if statement must be a boolean expression — Java does not accept int-as-boolean like C does.
  • In an if-else-if ladder, only the first true branch executes, even if later conditions are also true.
  • Always use braces around branches to avoid the dangling-else ambiguity and prevent future edits from breaking the logic.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering