Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 201 ยท Control Flow

if, else if and else

Make decisions in Java with if, else if and else - boolean conditions, nesting, guard clauses, brace style and classic bugs like = vs == and the dangling else.

So far your programs have run every statement from top to bottom. Real programs need to make decisions: charge shipping only for small orders, greet the user differently in the morning, reject a password that is too short. The if statement is how Java chooses whether to run a piece of code.

This lesson covers if, else and else if chains, how to nest them without creating a mess, the brace style professionals use, and the classic mistakes (several of which compile without a single warning).

The if statement

An if statement runs a block of code only when its condition is true:

Java
if (condition) {
    // runs only when condition is true
}

The condition goes in parentheses and must be a boolean expression: a comparison like age >= 18, a method like name.isBlank(), a boolean variable, or a combination with &&, || and ! (see Comparison and Logical Operators).

Java Your first if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Change the number in the Input box to 30 and run it again. IO.readln("Your age: ") prints a prompt and then reads a line.

Java has no "truthy" values. In some languages if (count) means "if count is not zero"; in Java it is a compile error, because count is an int, not a boolean. Write the comparison you mean: if (count != 0), if (name != null), if (!list.isEmpty()).

if and else

Two separate if statements with opposite conditions work, but they make Java test twice and you have to keep the two conditions in sync. else expresses "otherwise" directly. Exactly one of the two blocks runs:

Java
if (age >= 18) {
    IO.println("You can vote.");
} else {
    IO.println("You can vote in " + (18 - age) + " year(s).");
}

else if chains

When there are more than two possibilities, chain conditions with else if. Java tests them from top to bottom and runs the first block whose condition is true; the rest are skipped. The final else (optional) catches everything that didn't match:

Java Letter grades with else if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because the first match wins, the order of the conditions matters. The score >= 80 test doesn't need && score < 90: by the time Java reaches it, it already knows the score is below 90. If you put score >= 60 first, every passing score would get a D.

Notice also that grade is declared without a value but assigned in every branch. The compiler checks this (definite assignment, from Variables): remove the final else and the line IO.println(score + " -> " + grade) stops compiling, because grade might never have been assigned.

Nesting if statements

Any block can contain another if. Nesting is natural when a second question only makes sense after the first one is answered:

Java Nested decisions: shipping cost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The ?: in the inner branch is the conditional (ternary) operator from Operator Precedence and the Ternary Operator. Use it for short either/or values; use if for actions and anything longer.

Deep nesting quickly becomes hard to read: each level adds indentation and another condition you have to keep in your head. Two techniques flatten it.

Combine conditions

When the inner if has no else, the two conditions can usually be joined with &&:

Java
// Nested
if (user != null) {
    if (user.isAdmin()) {
        showAdminPanel();
    }
}

// Flat: && stops early, so user.isAdmin() never runs on null
if (user != null && user.isAdmin()) {
    showAdminPanel();
}

Guard clauses

Inside a method, handle the special cases first and return early. The main logic then sits at the left margin instead of three levels deep:

Java Guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each guard reads like a rule, and you can add a new rule without touching the others. Methods covers return in detail.

Brace style

Java's near-universal convention, used by the JDK, Google's style guide and practically every project:

  • The opening brace goes at the end of the if line; the closing brace on its own line.
  • else and else if go on the same line as the closing brace: } else {.
  • Indent the body by 4 spaces.
  • Always use braces, even for a one-line body.

Java allows you to omit the braces when the body is a single statement:

Java
if (balance < 0) IO.println("Overdrawn!");   // legal, but risky

The problem appears when someone adds a second line later. Indentation means nothing to the compiler; without braces, only the first statement belongs to the if:

Java Why braces matter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The fee message prints even though the balance is positive. This exact pattern has caused real security bugs in production software. With braces, the mistake is impossible.

Common mistakes

= instead of ==

= assigns, == compares. For int variables, Java catches the mistake because the result of if (x = 5) is an int, not a boolean:

Java
int x = 3;
if (x = 5) { }   // compile error: incompatible types: int cannot be converted to boolean

But with a boolean variable, the assignment produces a boolean, so it compiles and silently does the wrong thing:

Java The boolean assignment trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The fix is to never compare booleans with true or false at all: write if (isAdmin) and if (!isAdmin). It's shorter and the trap disappears.

A semicolon after the condition

A semicolon on its own is an empty statement. Put one after if (...) and it becomes the whole body; the block below is just an ordinary block that always runs:

Java
if (temperature > 30); {          // the ; ends the if
    IO.println("It's hot!");      // always prints
}

Most IDEs flag this; the compiler doesn't.

The dangling else

An else always belongs to the nearest unmatched if before it, regardless of indentation:

Java The dangling else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The indentation suggests "Out of stock." runs when stock > 0 is false, but the else actually pairs with if (onSale). Since stock is 0, the outer if skips everything and nothing prints. Braces make the intent explicit, which is one more reason to always use them:

Java
if (stock > 0) {
    if (onSale) {
        IO.println("In stock and on sale!");
    }
} else {
    IO.println("Out of stock.");
}

Other traps

  • Chained comparisons don't work. if (0 < x < 10) is a compile error, because 0 < x is a boolean and a boolean can't be compared to 10. Write if (x > 0 && x < 10).
  • Strings need equals. if (answer == "yes") compares references and often fails. Write if ("yes".equals(answer)) (see Comparing and Converting Strings).
  • Exact comparisons of double. 0.1 + 0.2 == 0.3 is false. Compare with a tolerance: Math.abs(a - b) < 1e-9 (see Working with Numbers).
  • Unreachable branches. In if (n > 10) ... else if (n > 20) ..., the second branch can never run. Order range checks from most specific to least.

When you find yourself writing a long else if chain that compares one value against many constants, a switch is usually clearer. That's the next lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int n = 15; if (n > 10) { IO.println("A"); } else if (n > 5) { IO.println("B"); } else { IO.println("C"); }

    Java runs only the first branch whose condition is true. 15 > 10 is true, so it prints A and skips the rest, even though 15 > 5 is also true.
  2. 2. Which line does NOT compile when count is an int?

    An if condition must be boolean. Java has no truthy values, so an int on its own is a compile error.
  3. 3. What does this print? boolean done = false; if (done = true) { IO.println("yes"); } else { IO.println("no"); }

    done = true assigns true and evaluates to true, so the if branch runs. Writing if (done) avoids this trap.
  4. 4. With int x = 5;, what does this print? if (x > 10) if (x > 20) IO.println("big"); else IO.println("small");

    The else pairs with the nearest if, if (x > 20). Since x > 10 is false, the whole inner if/else is skipped and nothing prints.
  5. 5. Why is if (score >= 80) enough for a B in a chain that starts with if (score >= 90) { ... } else if (score >= 80)?

    Conditions are tested top to bottom and the first true one wins, so any score that reaches the second test is already known to be below 90.

Summary

  • if (condition) { ... } runs a block only when the boolean condition is true; Java has no truthy values.
  • else handles "otherwise"; else if chains are tested top to bottom and only the first matching branch runs.
  • Flatten nested ifs by combining conditions with && or by returning early with guard clauses.
  • Always use braces: without them only the first statement belongs to the if, and an else binds to the nearest if.
  • Watch for if (flag = true), a stray ; after the condition, chained comparisons, == on strings and exact double comparisons.

Next: switch Statements and Expressions, where you'll choose between many cases cleanly, from classic fall-through to modern switch expressions.