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.
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
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.
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
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
elsebelongs to the nearest unmatchedif, whatever the indentation suggests. Braces make the intent explicit. - Assignment is not comparison.
if (x = 5)does not compile forint, butif (flag = true)for abooleandoes and always runs. Write==or justif (flag). - Compare strings with
equals(), not==:if ("yes".equals(answer))also avoids aNullPointerExceptionwhenanswerisnull. - 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 : cis an expression, handy for choosing a value; do not nest it deeply. - Many branches on one value are often clearer as a
switchexpression. - Pattern variables introduced by
instanceofare in scope only where the compiler can prove the match succeeded (Java 16+).
Related
switch,while,return- Lessons: if and else, Pattern matching