Java Else If Statement
The else if statement in Java allows you to check multiple conditions sequentially. If the first if condition is false, it checks the next else if condition, and so on.
Key Topics
1. Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}
2. Example
Example of using else if statements:
public class ElseIfExample {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 80) {
System.out.println("Grade B");
} else if (score >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
}
}
Key Takeaways
- Use
else ifto check multiple conditions in sequence. - The first condition that evaluates to
truewill have its code block executed. - If none of the conditions are true, the
elseblock (if present) will execute.