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? I can vote and drive.
  2. If I was 13 what would it print out? It wouldn’t print anything.
  3. Create your if statement with one else if condition.
// 3
int grade=9;
if(grade==9){
    System.out.println("I am a freshmen");
}
else if(grade==10){
    System.out.println("I am a sophmore");
}
else if(grade==11){
    System.out.println("I am a junior");
}
else if(grade==12){
    System.out.println("I am a senior");
}

I am a freshmen