0/30 Days Completed 0 Learning Days
Day 5 of 30 · Week 1 — Java Foundations
The switch statement
1 Learn
switch picks one of many options by comparing one value against fixed cases. It is handy for menus, days of the week or grades.
Each case usually ends with break. Without break, Java keeps running into the next case (called fall-through).
Use switch when you compare one variable to exact values. Use if/else for ranges like marks >= 60.
2 See the Code
Java
public class Menu {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1:
System.out.println("Tea");
break;
case 2:
System.out.println("Coffee");
break;
default:
System.out.println("Water");
}
}
}- choice is 2, so case 2 runs and prints Coffee.
- break stops the switch so case default is not run.
- default runs when no case matches.
Output
Coffee
3 Practice
- Write a switch that prints the name of the day for numbers 1 to 7, and Invalid for anything else.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. What does break do in a switch?
2. Which is better for checking marks >= 60?
Step 5
Answer and check the Quick Check above to unlock this.