Basic else-if chain

java
if (condition1) {
    // runs if condition1 is true
} else if (condition2) {
    // runs if condition1 is false AND condition2 is true
} else if (condition3) {
    // runs if conditions 1 & 2 are false AND condition3 is true
} else {
    // runs if ALL conditions are false
}

Grade classification example

java
int score = 85;

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");   // prints this
} else if (score >= 70) {
    System.out.println("C");
} else if (score >= 60) {
    System.out.println("D");
} else {
    System.out.println("F");
}

Why does 85 print "B" and not "C"?

else-if vs. independent if statements

Independent if statements (all checked)

java
int score = 95;

if (score >= 90) System.out.println("A");  // prints
if (score >= 80) System.out.println("B");  // also prints!
if (score >= 70) System.out.println("C");  // also prints!

else-if chain (only first match)

java
int score = 95;

if (score >= 90) System.out.println("A");       // prints — stops here
else if (score >= 80) System.out.println("B");  // skipped
else if (score >= 70) System.out.println("C");  // skipped

Order matters

Wrong order (too broad first)

java
int score = 95;

if (score >= 70) {
    System.out.println("C");   // 95 >= 70 is true → prints "C"!
} else if (score >= 80) {
    System.out.println("B");   // never reached for high scores
} else if (score >= 90) {
    System.out.println("A");   // never reached
}

Correct order (most restrictive first)

java
if (score >= 90)      → A
else if (score >= 80) → B
else if (score >= 70) → C
else                  → F

The optional else

java
// Without else — nothing happens if all conditions are false
if (day == 1) System.out.println("Monday");
else if (day == 2) System.out.println("Tuesday");
// If day is 5, nothing prints

// With else — always produces output
if (day == 1) System.out.println("Monday");
else if (day == 2) System.out.println("Tuesday");
else System.out.println("Other day");

Tracing practice

java
int x = 15;
String category;

if (x > 100) {
    category = "large";
} else if (x > 50) {
    category = "medium";
} else if (x > 10) {
    category = "small";
} else {
    category = "tiny";
}
System.out.println(category);

Complete example: Season detector

java
public class SeasonDetector {
    public static void main(String[] args) {
        int month = 7;
        String season;
        
        if (month == 12 || month == 1 || month == 2) {
            season = "Winter";
        } else if (month >= 3 && month <= 5) {
            season = "Spring";
        } else if (month >= 6 && month <= 8) {
            season = "Summer";
        } else if (month >= 9 && month <= 11) {
            season = "Fall";
        } else {
            season = "Invalid month";
        }
        
        System.out.println("Month " + month + ": " + season);
        // Output: Month 7: Summer
    }
}

AP Exam Tips

Common Mistakes

Key Vocabulary