Java ยท Chapter 13 of 42

Java If...Else

The if statement executes a block of code only if a condition is true. else provides an alternative block, and else if lets you chain multiple conditions.

Java also has a ternary operator `condition ? valueIfTrue : valueIfFalse` for compact conditional expressions.

Syntax
if (condition) {
} else if (condition2) {
} else {
}

if, else if, else

Conditions are evaluated top to bottom; the first true branch executes and the rest are skipped.

Ternary operator

The ternary operator condenses a simple if/else into a single expression, often used for quick assignments.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    int age = 20;
    if (age >= 18) {
      System.out.println("Adult");
    } else {
      System.out.println("Minor");
    }
    String status = (age >= 18) ? "Adult" : "Minor";
    System.out.println(status);
  }
}
Output
Adult
Adult

An if/else prints Adult since age is 20, then the ternary operator produces the same result.

Key points

  • if executes code only when a condition is true.
  • else if chains additional conditions.
  • else runs when no prior condition matched.
  • The ternary operator is a compact if/else expression.
๐Ÿ’ก Note: Braces are optional for single-statement blocks but recommended for clarity.

๐Ÿ“ Quick Quiz

1. What does else if allow?

2. What does the ternary operator return?

3. When does the else block run?