Codectionary / Developer documentation / Java

if / else if / else

The if statement executes a block of code only when its condition evaluates to true. Java lets you chain additional conditions with else if, and provide a fallback with else for when none of the preceding conditions match. Unlike some languages, Java requires the condition to be an actual boolean expression - it cannot use a number or object directly as a truthy/falsy value.

Syntax

if (condition) {\n  // code\n} else if (condition2) {\n  // code\n} else {\n  // code\n}

Examples

Basic if / else

Choosing between two branches based on a condition.

int age = 20;

if (age >= 18) {
    System.out.println("You are an adult");
} else {
    System.out.println("You are a minor");
}

Chaining with else if

Testing multiple conditions in sequence.

int score = 75;

if (score >= 90) {
    System.out.println("Grade: A");
} else if (score >= 80) {
    System.out.println("Grade: B");
} else if (score >= 70) {
    System.out.println("Grade: C");
} else {
    System.out.println("Grade: F");
}

Nested Conditionals

Placing an if statement inside another to check compound conditions.

int age = 25;
boolean hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        System.out.println("You can drive");
    } else {
        System.out.println("You need a license first");
    }
} else {
    System.out.println("You are too young to drive");
}

Best practices

  • Always use curly braces {} even for single-statement blocks - it prevents subtle bugs when code is later added to a branch
  • Order else if conditions from most specific to least specific when ranges overlap, since Java checks them top to bottom
  • Flatten deeply nested if statements where possible by combining conditions with && or using early returns
  • Consider a switch statement instead of a long else if chain when comparing a single variable against many discrete values

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading