Concept Explanation
If if-else is a fork in the road, switch is an Elevator Panel. Instead of checking "Is it floor 1? Is it floor 2? Is it floor 3?" you just press the button for the floor you want and go directly there.
It's much faster and cleaner when you have many specific options (like days of the week or menu items).
Syntax or Core Structure
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}
The 'break' keyword
Crucial! If you forget break, Java will keep running the code for the next cases even if they don't match. This is called "Fall-through."
Best Practices
- Always include a 'default': It's the "Catch-all" for when none of the cases match.
- Modern Switch (Java 14+): Research "Switch Expressions" (
yieldand arrows->) which make switch statements much more powerful. - Use for Enums: Switch works perfectly with Enum types (like
Color.RED).
Practice Exercises
- The Month Name: Write a switch statement that converts a number (1-12) into a Month name.
- The Calculator: Use a switch statement to perform
+,-,*, or/based on achar operatorvariable. - The Fall-through: Write a switch statement for "Workdays vs Weekends" where cases 1-5 all do the same thing by intentionally omitting
break.