Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

if / else

Runs a block of code only if a condition is true.

Available since: Java 1.0

Syntax

if (condition) { … } else if (condition) { … } else { … }

Examples

A chain of conditions:

void main() {
    int score = 72;
    if (score >= 90) {
        IO.println("A");
    } else if (score >= 70) {
        IO.println("B");
    } else {
        IO.println("C");
    }
}

Output:

B

Notes

The condition must be a boolean: unlike C or JavaScript, Java does not accept if (count) for a number — write if (count > 0). Braces can be omitted for a single statement, but it is better to always use them.

See also

  • ? : — Picks one of two values by a condition — a short form of if-else.
  • switch — Picks a branch by value; as an expression it returns a result.
  • && || ! — Logical AND, OR and NOT for boolean values.

In the tutorial

  • Conditions — Branching in Java: if, else, else if, compound conditions and the ternary operator.

Thanks for reading!

Donate to the site — we work hard for you.