The <code>if</code> / <code>else</code> Statement in Java

if / else if / else is Java's basic conditional. The condition must be a boolean β€” Java doesn't coerce integers, strings or nulls into booleans.

Syntax

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

Braces are optional β€” but do use them

if (x > 0) doA();
else       doB();

// Without braces, the classic bug:
if (x > 0)
    doA();
    doB();            // always runs β€” not in the if!

Always use braces. Many style guides enforce it.

Ternary β€” when the branches are simple values

String label = active ? "ON" : "OFF";
int abs = n >= 0 ? n : -n;

Nesting ternaries more than one level becomes unreadable β€” use if/else or a switch.

Long chains β€” reach for a switch expression

// Readable chain
String label = switch (day) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
    case SATURDAY, SUNDAY                              -> "Weekend";
};

Common mistakes

  • Assignment instead of comparison β€” if (x = 5) won't compile for non-boolean types but does for booleans: if (done = true) silently assigns. Use ==.
  • No braces β€” the "dangling else" and "second statement escaped the if" bugs both disappear with braces.
  • Boolean equals true β€” if (active == true) is just if (active).

Related

Pillar: Java control flow. See also switch, ternary operator.