0/30 Days Completed 0 Learning Days
Day 4 of 30 · Week 1 — Java Foundations
if, else if, else
1 Learn
Programs often need to make decisions. An if statement runs a block only when its condition is true.
else if checks another condition when the earlier ones were false. else runs when none of the conditions were true.
Java checks the conditions from top to bottom and runs only the first matching block.
2 See the Code
Java
public class Grade {
public static void main(String[] args) {
int marks = 72;
if (marks >= 80) {
System.out.println("Distinction");
} else if (marks >= 60) {
System.out.println("First class");
} else if (marks >= 35) {
System.out.println("Pass");
} else {
System.out.println("Try again");
}
}
}- 72 >= 80 is false, so Java moves on.
- 72 >= 60 is true, so it prints First class and skips the rest.
Output
First class
3 Practice
- Write a program that prints Positive, Negative or Zero for a given number.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. When does the else block run?
2. If marks = 90 above, what prints?
Step 5
Answer and check the Quick Check above to unlock this.