3.4 Else If Statements

Else If Statements: Used when you have multiple conditions that need to be checked sequentially.

Flow of Execution: Each condition is evaluated in the order written. The first true condition’s code runs, and the rest are skipped.

Structure:

  • Start with a single if statement.
  • Follow with as many else if statements as needed.
  • Optionally end with one else to handle any remaining cases. Key Concept: The order of conditions matters. More specific conditions should come before broader ones to ensure accurate results.

image

  1. If I was 19 what would it print out?
  2. If I was 13 what would it print out?
  3. Create your if statement with one else if condition.
if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Code if none of the above conditions are true
}
|   if (condition1) {

cannot find symbol

  symbol:   variable condition1



|   } else if (condition2) {

cannot find symbol

  symbol:   variable condition2
public static void main(String[] args) {
    int age = 19;

    if (age >= 18) {
        System.out.println("You are an adult.");
    } else if (age >= 13) {
        System.out.println("You are a teenager.");
    } else {
        System.out.println("You are a child.");
    }
}
public static void main(String[] args) {
    int temperature = 85;

    if (temperature >= 90) {
        System.out.println("It's really hot outside.");
    } else if (temperature >= 70) {
        System.out.println("It's a warm day.");
    } else {
        System.out.println("It's cold outside.");
    }
}