else and else if
- Java course
- Beginner
- Lesson 37/116
- 4 min
Learn alternatives with else and else if.
else and else if
When the if condition is false, the else block runs. For multiple conditions use an else if chain.
int score = 40;
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}With else if, conditions are tested in order; the first true block runs. Java has no elif keyword; it always uses else if as two words.
The else if chain
For three or more branches use an else if chain. Conditions are tested top to bottom; the first true one runs:
int score = 75;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 80) {
System.out.println("Good");
} else if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}Branches after the first true one are skipped. else goes last and is optional.
Practice Compute a grade
Write a Main class with a main method. Assign 85 to int score. With if (score >= 90) print "Excellent", else if (score >= 80) print "Good", else print "Average". Use System.out.println in each block.
Sample solution
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Excellent");
} else if (score >= 80) {
System.out.println("Good");
} else {
System.out.println("Average");
}
}
}Expected output
Good
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the else block
int score = 40;
if (score >= 50) {
System.out.println("Pass");
} ____ {
System.out.println("Fail");
}
int score = 40;
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
Explanation: else runs when if is false.
2 int x = 0; if (x > 10) { A } else if (x > 3) { B } else { C } — which is printed?
- A
- B
- None
- C Correct answer
Explanation: x=0 matches no condition; else (C) runs.
3 Match the else concepts
| Term | Meaning |
|---|---|
if |
First condition |
else if |
Second condition |
else |
Fallback |
{ } |
Block |