How to make decisions with if/else

Write an if statement

The body runs only when its condition is true. Braces keep the block clear even when it has one statement.

int temperature = 28;
if (temperature > 25) {
    System.out.println("It is warm.");
}

Add an alternative

An else block handles the case where the condition is false.

int number = 7;
if (number % 2 == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

Test several branches

An else if chain stops at the first true condition, so order the tests carefully.

int score = 82;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C or below");
}

Use a conditional expression

The ternary operator selects one of two values. Use it for simple expressions, not complicated branching.

int age = 20;
String status = age >= 18 ? "adult" : "minor";