Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

The if and else statements

Reference for Java if, else if and else: how conditions are evaluated, the dangling else rule, braces, the ternary operator and common mistakes.

The if statement runs a statement only when a boolean condition is true. An optional else branch runs when the condition is false. Chaining else if lets you test several conditions in order; the first one that is true wins and the rest are skipped.

The condition must be of type boolean or Boolean. Unlike C or JavaScript, Java does not treat numbers, strings or null as true or false, so if (count) is a compile error.

Java
if (condition) {
    // runs when condition is true
} else if (otherCondition) {
    // runs when the first was false and this one is true
} else {
    // runs when all conditions were false
}

Try it

Java Choosing a branch

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.

Java Short-circuiting and the ternary operator

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.

Syntax

Java
if (booleanExpression) statement
if (booleanExpression) statement else statement
Part Description
booleanExpression Must evaluate to boolean or Boolean. A null Boolean throws NullPointerException when unboxed.
statement A single statement or a block in braces.

Usage notes

  • Always use braces. Without them only the next statement belongs to the if. Adding a second line later is a classic bug; braces prevent it.
  • Dangling else: an else belongs to the nearest unmatched if, whatever the indentation suggests. Braces make the intent explicit.
  • Assignment is not comparison. if (x = 5) does not compile for int, but if (flag = true) for a boolean does and always runs. Write == or just if (flag).
  • Compare strings with equals(), not ==: if ("yes".equals(answer)) also avoids a NullPointerException when answer is null.
  • Short-circuit operators && and || evaluate the right side only if needed; the non-short-circuit & and | always evaluate both sides.
  • Definite assignment: a local variable assigned in every branch (including a final else) can be used afterwards; the compiler checks this.
  • Ternary operator a ? b : c is an expression, handy for choosing a value; do not nest it deeply.
  • Many branches on one value are often clearer as a switch expression.
  • Pattern variables introduced by instanceof are in scope only where the compiler can prove the match succeeded (Java 16+).